Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

Sum all integers in a string C++

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely

I guess you were given a good advice. With std::istringstream you could just read in values one after the other as you would read them from the standard input (or any other input stream).

For instance:

#include <sstream>
#include <string>
#include <iostream>

int main()
{
    // Suppose at some time you have this string...
    std::string s = "1 2 3 4 5 6 7 8 9 10";

    // You can create an istringstream object from it...
    std::istringstream iss(s);

    int i = 0;
    int sum = 0;

    // And read all values one after the other...
    while (iss >> i)
    {
        // ...of course updating the sum each time
        sum += i;
    }

    std::cout << sum;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...