I am trying to convert some strings from a file into integers and doubles using stoi()
and stod()
. However, I keep getting an error which terminated my program.
Here is a screenshot of what happens when I run the code I included below.
The variable ageString
, which I am trying to stoi
, is = 100
.
As you can see in the screenshot, it actually converts 100
into an integer and prints it out. Cool, that's exactly what I want.
But for some reason it is giving me an error saying invalid_argument
. How is 100
an invalid_argument
for stoi()
?
I already made sure to #include
string and to use namespace standard
.
I've tried running my code on code::blocks
and Repl.it
using c++ 11. The results are the same.
I've tried using stoi()
on a random number string (not from my file) like 1234
and it still doesn't work.
My .txt
file looks like this (single space):
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();
I expect the code to end by printing run this code
, but it actually ends by printing hello
.
Error message:
terminate called after throwing an instance of 'std::invalid_argument' what(): stoi"