Reputation: 31
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());
Upvotes: 3
Views: 113
Reputation: 41820
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.
Upvotes: 0
Reputation: 234845
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();
Upvotes: 3