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

Sum all integers in a string C++

本文关键字:整数 求和 字符串 C++      更新时间:2023-10-16

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

"1 2 3 4 5 6 7 8"

我知道字符串是由一个空格字符分隔的整数组成的。我如何对它们求和?

我是一个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];
}

我怎么能在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;
}

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

1
3 4
8 1 1
7 2 9 3
1 1 1 1 1
0 1 2 5 6 10

因此,对于每一行,程序必须打印字符串行中所有整数的和。此示例将生成:

1
7
10
21
5
24

感谢

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

我想你得到了一个很好的建议。使用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;
}

像这样:

std::stringstream s("1 2 3 4 5 6 7 8 9");
int n = 0;
int x;
while (s >> x)
    n += x;
std::cout << n << std::endl;

编辑后:

cout << start << endl;

这是错误的,您应该打印sum而不是:

cout << sum << endl;

我使用C代码来解决这个问题。以下是最终解决方案:

#include <stdio.h>
#include <string.h>
int main() {
    char *c;
    char line[100];
    int x, sum = 0;
    while(gets(line)) {
        for(c = strtok(line, " "); c ; c = strtok(NULL, " ")) {
            sscanf(c, "%d", &x);
            sum += x;
        }
        printf("%dn", sum);
        sum = 0;
    }
    return 0;
}

希望它能帮助任何可能有同样问题的人!