Stoi causing R6010 abort()
I'm trying to convert a string into a integer and when I call stoi(line) it causes the program to crash.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int main()
{
vector<int> numbers;
int i;
string line;
ifstream myfile ("example.dat");
if (myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile, line);
cout << line << endl;
i = stoi(line);
cout << i << endl;
}
}
else
{
cout << "Was unable to open the file" << endl;
}
myfile.close();
|
The file being read from looks like:
1 2 3 4 5 6 7 8
|
3
12
23
34
12 34
12 12
34 23
23 23
|
You are not checking to see if your input was successful before you feed it to std::stoi.
Maybe you should do so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
int main()
{
std::vector<int> numbers;
std::string line;
// ifstream myfile ("example.dat");
std::istringstream myfile(
"3\n"
"12\n"
"23\n"
"34\n"
"12 34\n"
"12 12\n"
"34 23\n"
"23 23\n\n"
);
while ( std::getline(myfile, line) )
{
try {
int num = std::stoi(line) ;
std::cout << "Converted \"" << line << "\" to " << num << '\n' ;
}
catch( std::exception& ex)
{
std::cout << "ERROR: " << ex.what() << '\n' ;
std::cout << "\tUnable to convert \"" << line << "\" to a number.\n" ;
}
}
}
|
http://ideone.com/X4UKyP
Topic archived. No new replies allowed.