stoi()和stod()正在终止我的程序,我实际上不知道为什么

时间:2019-05-24 05:53:03

标签: c++

我正在尝试使用stoi()stod()将文件中的某些字符串转换为整数和双精度。但是,我不断收到错误消息,终止了我的程序。

这是我运行下面包含的代码时发生的屏幕截图。

我要尝试ageString使用的变量stoi是= 100

如您在屏幕快照中所见,它实际上将100转换为整数并打印出来。太酷了,这正是我想要的。

但是由于某种原因,它给我一个错误,提示invalid_argument100invalid_argument的{​​{1}}如何?

我已经确保输入stoi()字符串并使用命名空间#include

我尝试使用c ++ 11在standardcode::blocks上运行代码。结果是相同的。

我尝试对Repl.it这样的随机数字符串(不是从我的文件中)使用stoi(),但仍然无法正常工作。

我的1234文件看起来像这样(单个空格):

.txt
TEST NAME
M
100
200
300
1

我希望代码以打印//This is the body of my function. //I've added several cout statements just to help me debug. //In my actual function I don't plan to have any couts. std::ifstream inputFile; inputFile.open(fileName); std::string name, sex; int age, activityLevel, calories; double height, weight; while(inputFile.good()) { using namespace std; string ageString, heightString, weightString, activityString; getline(inputFile, name, '\n'); getline(inputFile, sex, '\n'); getline(inputFile, ageString, '\n'); getline(inputFile, heightString, '\n'); getline(inputFile, weightString, '\n'); getline(inputFile, activityString, '\n'); cout << endl << name //All of this prints fine, << endl << sex //just like it's written in the file. << endl << ageString << endl << heightString << endl << weightString << endl << activityString; cout << endl << endl << stoi(ageString); //This converts and prints cout << endl << endl << "hello"; //This also prints } std::cout << "run this code"; //The program stops working here. inputFile.close(); 结尾,但实际上以打印run this code结尾。

错误消息:

  

在抛出“ std :: invalid_argument” what():stoi的实例后调用终止。

1 个答案:

答案 0 :(得分:0)

我认为您的代码在while循环中再次被迭代。为确保它仅按预期进行1次迭代,请添加更多cout进行检查。例如:我认为您的代码将打印start reading input 2次,然后终止您的程序。如果是这样,则需要考虑使用inputFile.good()

while(inputFile.good())
{

    using namespace std;
    cout << "start reading input" << endl;
    string ageString, heightString, weightString, activityString;

    getline(inputFile, name, '\n');
    getline(inputFile, sex, '\n'); 
    getline(inputFile, ageString, '\n');
    getline(inputFile, heightString, '\n');
    getline(inputFile, weightString, '\n');
    getline(inputFile, activityString, '\n');

    cout << endl << name             //All of this prints fine,
         << endl << sex              //just like it's written in the file.
         << endl << ageString
         << endl << heightString
         << endl << weightString
         << endl << activityString;

    cout << endl << endl << stoi(ageString); //This converts and prints

    cout << endl << endl << "hello"; //This also prints

}