0
votes

This is my code:

int main()
{
std::ifstream myfile;
myfile.open("ex.txt");
std::string a;
while(myfile.eof()!=1)
{
    getline(myfile,a,',');
    int i = stoi(a);
    if (!(i%2))
      std::cout<<a<<std::endl;
}

}

Basically I have a text file with comma separated integers. I now wish to display even of these integers. I am running the code on Xcode , Apple LLVM. I get the correct output but Xcode shows some wierd exception:

libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion Program ended with exit code: 0

This message comes with a breakpoint on the stoi command. Whats happening? And how can I do this smoothly?

Edit: Input text File.

5,8,4,8,0,8,4,3,0,7,8,3,6,2,9,7,3,0,9,0,1,9,2,4,5,4,9,8,4,3,0,9,3,3,5,1,1,8,6,3,4,6,8,2,0,2,6,2,1,6,6,1,9,4,1,1,2,9,3,0,3,2,3,9,4,8,0,3,2,2,6,9,1,1,8,1,0,3,6,3,0,3,2,8,6,5,0,3,7,4,3,3,6,0,1,2,2,8,2,5,1,0,0,2,8,8,3,3,8,9,2,3,6,2,5,0,2,4,6,2,6,1,0,2,6,7,1,2,1,8,5,2,2,3,4,2,7,1,7,3,3,8,9,3,2,9,9,5,1,3,4,2,2,0,1,3,0,8,3,4,7,4,5,5,6,4,0,7,8,0,1,1,8,5,2,7,4,4,6,3,4,4,8,3,4,1,1,1,9,2,5,1,3,4,2,6,4,8,7,2,

No \n i.e. linee changes

2
while(myfile.eof()!=1) NoooooooooooooooooLightness Races in Orbit

2 Answers

1
votes

I believe this has to do with the fact that you're using while (!eof()). This is an erroneous expression to use as a condition as it doesn't conform to the intended functionality of IOStreams. You should be checking if the input succeeded before the input is performed:

while (std::getline(myfile, a, ','))

Doing otherwise causes the stream to reach the end-of-file and for the string a to be without a value. This empty string is then passed to std::stoi, causing an exception to be thrown.

0
votes

It's an exception, and you have no code to catch exceptions.

  • Add code to catch exceptions

It's thrown because std::stoi is getting an invalid argument. In this case, you have at least one guaranteed case where that will happen and that's on your last loop iteration. It's because you're looping for input incorrectly, as been covered on SO many times.

Do not write while (!stream.eof()) or its equivalents (which learning resource instructed you to do that?). EOF is set when a read fails at EOF, not when the next read will fail. Consequently you end up with one getline too many.

  • Write while (getline(...)) instead.