如何转换并找到具有多个数字的字符串的总和

How do I convert and find the sum of a string with multiple numbers?

本文关键字:数字 字符串 何转换 转换      更新时间:2023-10-16

>我正在做一个项目,我必须从文本文件中找到字符串中一系列数字的总和。我创建了代码,我通常可以调用函数来转换某些行,但它只对第一个数字这样做。

如何修改我的代码,以便我可以添加字符串中的所有数字,而不仅仅是第一个数字?

文中的行是:

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对解决方案的建议。