3

I have to make a program that reads information for a student from a file, and I made a couple of vectors to keep all that information. But then I need to sum up the absences of all the students, so I need to convert them to integer, however when I try to the program runs, but crashes immediately when it reaches the atoi part.

while(!read.eof()) {
    if(i==4){
        i=0;
    }

    read>>b;

    if(i==0){ names.push_back(b); }
    if(i==1){ last_name.push_back(b); }
    if(i==2){ absences.push_back(b); }
    if(i==3){ unatoned.push_back(b); }
    i++;
}

int a = atoi(absences[0].c_str());
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Ruzzle
  • 31
  • 2
  • 1
    First of all, please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Mar 04 '19 at 13:36
  • 1
    Secondly, why the `if` and the indexes? Why not simply read the four values directly? As in `while (read >> first_name >> last_name >> absence >> unatoned) { ... }`? Then the variables could be of the correct type to begin with, and you don't need to do any conversion. And please learn about *structures* and *classes*. – Some programmer dude Mar 04 '19 at 13:37
  • Instead of the old `atoi`, try to use `stoi` (described on http://www.cplusplus.com/reference/string/stoi/ ), and if that still does not work, catch the exceptions that it can throw (see link) and see which one it was. Also have some test case for us, that is what you entered and also printing the content of `absences[0]`, which you then post here. Since in some comment you say that you have checked it, it might be that it has some control characters in it which confuse `atoi`. (By the way, the OOP approach would be to have a `class Student` and either `vector` or `class Students`.) – Aziuth Mar 04 '19 at 14:39

2 Answers2

3

If absences remains empty then the behaviour of absences[0] is undefined.

Using absences.at(0) when absences is empty forces the compiler to throw an exception so is easier to work with.

Either way, for the number of absences, use simply

auto a = absences.size();
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

You should change you absences vector to be a vector of int:

std::vector<int> abscences;

// rest of the code...

The read >> var instruction will take care of the conversion.

Of course, the >> operator will not write into the integer if it's invalid.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141