对字符串C++中的所有整数求和

rod*_*ves -1 c++ string text split

我的代码中有一个C++字符串,如:

"1 2 3 4 5 6 7 8"
Run Code Online (Sandbox Code Playgroud)

我知道字符串由用空格char分隔的整数组成.我如何总结它们?

我是一个C++新手,在Java中我只是这样做:

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];
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在C++中使用我的字符串对象?

有些人建议我,stringstream但我仍然无法理解这个对象,我需要完全读取字符串,获取其中的每一个数字.

提前致谢!

更新:一些人很好地试图帮助我,但仍然没有工作.也许是因为我的问题的一些怪癖,我以前没有澄清过.所以这里:

#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;
}
Run Code Online (Sandbox Code Playgroud)

啊,输入文件包含以下内容:

1
3 4
8 1 1
7 2 9 3
1 1 1 1 1
0 1 2 5 6 10
Run Code Online (Sandbox Code Playgroud)

因此,对于每一行,程序必须打印字符串行中所有整数的总和.这个例子会生成:

1
7
10
21
5
24
Run Code Online (Sandbox Code Playgroud)

谢谢

And*_*owl 5

有些人建议我使用stringstream,但我仍然无法理解这个对象,我需要完全读取字符串

我猜你得到了一个很好的建议.有了std::istringstream你只可以在其他后读入一个值,你会从标准输入(或其他任何输入流)阅读.

例如:

#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;
}
Run Code Online (Sandbox Code Playgroud)