0

I'm trying to read strings from a file and initializing objects (from type "Movimentacao") with this strings and putting these objects into a vector. To do that, I have to transform some strings into ints but when I try to execute the program, it shows this error:

terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi

The code compiles normally and, with some couts to debbug, I found that the loop executes one time, but in the second time, it stops on the line with the "stoi" command.

while(!mov.eof()){
            getline(mov, dia, ',');
            getline(mov, mes, ',');
            getline(mov, ano, ',');
            getline(mov, desc, ',');
            getline(mov, sigla, ',');
            getline(mov, val, ',');
            sig = sigla[0];
            Movimentacao M(stoi(dia), stoi(mes), stoi(ano), desc, sig, stod(val));
            movi.push_back(M);
        }
Rehwagen
  • 1
  • 1
  • 3
  • 1
    As the error says, you have invalid input into `stoi`. You need to make sure the content you are converting is a valid `int`. – NathanOliver Oct 03 '19 at 16:45
  • 1
    It's not clear from the code what the problem is exactly, but it may be related to [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) You should make sure each `getline` succeeded. – François Andrieux Oct 03 '19 at 16:45

2 Answers2

0

What you know is that the stoi() function threw an exception. What you don't know is why, or with what input.

Note that you're not testing missing data. You're not testing the state of the stream after each getline(). And you're not testing the size of the string it read. What happens, for example, if the file has missing elements: ,,,?

To answer your exact question, you'll want to catch the exception and examine the exception object. Likely, though, that won't help much: it might tell you the input, but not the state of the stream or where it was taken from.

What I suggest instead is two loops: an outer one to instantiate Movimentacao, and an inner one to collect the inputs and prepare them. Wrap the inner one in try/catch, and you'll be able to reconstruct the state of the stream -- especially its position -- when the error is encountered.

James K. Lowden
  • 6,629
  • 1
  • 13
  • 28
0

It ended up being a problem on the while(!eof) function. After modifying it it started working perfectly, Thanks everyone for the help!

Rehwagen
  • 1
  • 1
  • 3