I’m having a bit of trouble with a school assignment for C++. The specific problem I’m having involves reading lines from a file that contain a series of between 5 and 6 grades. The grades for each student appear together in a single line following the student’s name and id number. The challenge here is that the grades can have a variable number of spaces between them, and that if there are only 5 grades present, an error message needs to be generated to screen but the program is to continue running and average the 5 grades. Example of input: 23 46 68 85 98
I got the student name and id easily, but the string of digits is giving me problems. My plan was to getline and then tokenize the string and assign each token to a cell in an array. This works fine for 6 grades, but when only 5 grades are present it is assigning garbage to the sixth cell.
Here is the snippet of code that concerns this section:
fin.getline(gradeList, 200);
grade = strtok (gradeList, " ");
while (grade != '\0')
{
gradeArr[cycler] = atoi(grade);
grade = strtok(NULL, " ");
cycler++;
}
I tried doing an isdigit check on each token before converting it to an int, and writing a 0 in for any token that failed the isdigit check, but that didn’t work at all. It seems like it is pulling the name from the next line when only 5 grades are present and then when it atoi’s it, it changes it to a huge number.
I thought that when the program did getline, it would only grab the line until it saw the endline terminator. Is this not what is happening?
If you use
strtolorstrtod, it gives you back a pointer to the end of what you just processed, so you can continue from there. No tokenization necessary 🙂But it sounds like your problem is that you’re reading the wrong line. Print out thegradeListvariable before you start parsing.You should end up with something like this: