how to add up some numbers?

Is it possible to add up an uknown amount of double numbers from a string in a single value?

Ex: I: 1,2 3,5 7 8
O: 19,7

Thanks everyone!
Yes.

for example using stringstreams:
1
2
3
4
5
6
std::string str("1,2 3,5 7 8 ");
std::istringstream x(str);
double temp;
double accumulator(0);
while(x >> temp)
    accumulator += temp;

EDIT: Thanks Chervil. I have fixed my code. Guess I should sleep now.
Last edited on
The example is correct, but there's a minor typo, the last line should read:
 
    accumulator += temp;

and line 2 should read:
 
std::istringstream x(str);
Last edited on
Thanks for the code!

Can you explain a bit please?
A istringstream allows input to be read in from a string, in the same way as from cin or from a file.

These two lines do most of the work (though the preceding lines set everything up)
1
2
while(x >> temp)
    accumulator += temp;

Here it is reading a number from the stringstream x into the variable temp
then temp is added to the accumulator. The while loop ends when there are no more numbers in the stringstream.

Topic archived. No new replies allowed.