Задача: дана строка с числами через запятую.
Нужно:
вывести числа на экран по отдельности.
вычислить сумму чисел
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string str = "12,1,214,3234";
string s;
vector <int> vec;
int x;
for (int i = 0; i < str.length(); i++)
{
if (str[i] != )
{
s = s + str[i];
}
else
{
cout << s << endl;
x = atoi(s.c_str());
s.clear();
vec.push_back(x);
}
}
cout << s << endl;
x = atoi(s.c_str());
s.clear();
vec.push_back(x);
int sum = 0;
for (auto item : vec)
{
sum = sum + item;
cout << item << " ";
}
cout << endl << "Сумма чисел в строке = " << sum << endl;
return 0;
}
После запуска программы результат будет таким:
12 1 214 3234 12 1 214 3234 Сумма чисел в строке = 3461 C:\Users\ao\source\repos\vector_01.exe (process 144128) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
В уроке ниже есть всё, что описано в статье кроме более быстрого перебора элеметов вектора.
Share in social media:
|