I have a C++ string in my code that is like:
"1 2 3 4 5 6 7 8"
I know the string is composed of integers separated by a space char. How can I sum them?
I'm quite a C++ newbie and in Java I'd simply do:
String str = "1 2 3 4 5 6 7 8";
int sum = 0;
for (int i = 0; i < str.split(" ").length; i++ {
sum += Integer.parse(str.split(" ")[i];
}
How can I do just like this with my string object in C++?
Some people suggested me stringstream
but I still can't understand this object and I need to read the string entirely, getting every single digit within it.
Thanks in advance!
Update: some guys nicely tried to help me but still it's not working. Perhaps because of some quirk of my problem which I haven't clarified before. So here it goes:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
freopen("variable-exercise.in", "r", stdin);
int sum = 0, start = 0;
string line;
while(getline(cin ,line)) {
istringstream iss(line);
while(iss >> start) {
sum += start;
}
cout << start << endl;
sum = start = 0;
}
return 0;
}
Ah, the input file contains the following:
1
3 4
8 1 1
7 2 9 3
1 1 1 1 1
0 1 2 5 6 10
So, for each line, the program must print the sum of all integers in the string line. This example would generate:
1
7
10
21
5
24
thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…