从中间器转换字符串不起作用,出了什么问题?

Converting a string from an interger isn't working, whats going wrong?

本文关键字:什么 问题 不起作用 中间 转换 字符串      更新时间:2023-10-16

我似乎无法弄清楚导致问题的原因。我希望该程序从文件中读取数字列表,打印出列表,然后总计所有数字,但是当我尝试找到总数时,我无法将字符串值转换为整数值

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int total = 0;
    string line;
    ifstream myfile;
    myfile.open("random.txt");
    while (getline(myfile, line)) {
        cout << line << endl;
        total = total + static_cast<int>(line);
    }
    cout << total;
}

如果您使用的是C++ 11尝试stoi

total = total + stoi(line);

您可能想要

total = 0;
for (int i = 0; i < line.length(); ++i) {
  total = total + static_cast<int>(line[i]);
}

编辑:我误解了这个问题。以下代码应起作用。输入文件是

11 22

10

结果是43。

 #include <iostream>
 #include <fstream>
 #include <sstream>
 using namespace std;
int main()
{
    int total = 0;
    string line;
    ifstream myfile;
    int line_int = 0;
    myfile.open("random.txt");
    while (getline(myfile, line)) {
      cout << line << endl;
      istringstream iss(line);
      while(iss >> line_int)
        total = total + line_int;
    }
    cout << total;
}