对字符串C++中的所有整数求和
Sum all integers in a string C++
我的代码中有一个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;
}
希望它能帮助任何可能有同样问题的人!
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- 向量值(字符串和整数)求和C++
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 如何在C++中对大数据整数进行加法、求和、乘法和除法运算
- C++对字符和整数求和
- 用于从包含最大求和的整数数组中提取子数组的算法
- 对字符串C++中的所有整数求和
- C++将字符串数组转换为整数,然后求和int数组
- 对数组中的奇数和偶数整数求和