如何转换并找到具有多个数字的字符串的总和
How do I convert and find the sum of a string with multiple numbers?
>我正在做一个项目,我必须从文本文件中找到字符串中一系列数字的总和。我创建了代码,我通常可以调用函数来转换某些行,但它只对第一个数字这样做。
如何修改我的代码,以便我可以添加字符串中的所有数字,而不仅仅是第一个数字?
文中的行是:
34.4 5416.9 1541.9 154.7 816.98
我的代码如下:
#include <iostream>
#include<string>
#include<fstream>
#include <stdlib.h>
using namespace std;
string GetTotal ()
{
string total;
ifstream login("textfile.txt");
for(int i = 0; i < 6; ++i) // line 6 is where the numbers I need to add are
{
getline(login, total);
}
return total;
}
int main ()
{
string total = GetTotal ();
double data;
data = atof(total.c_str()); //convert to double
cout << data;
return 0;
}
输出为 34.4。
为了重申我的问题,我应该采取什么步骤才能将字符串中的数字相加?
istringstream ss(total);
vector<double> numbers;
double x;
while (ss >> x)
{
numbers.push_back(x);
}
现在你有一个所有数字的向量。其余的应该很容易!
当前代码只返回输入流的第一个元素,即 34.4。这是因为atof()
将字符串消耗到第一个空白。
考虑@Neil对解决方案的建议。
相关文章:
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值