I am trying to read a file into an array[50] that has a students name followed by their grade. Example of the input file: Bob 99.5 Kim 87.3 Jack 94.8 Kyle 98.5 ect...
I do not know how many entries are in the file and I need to find the average grade there for I must count the entries as they are read in. so far my code looks like this:
1 2 3 4 5 6 7 8 9 10
counter = 1;
inFile >> studentName[0];
while (inFile)
{
inFile >> studentName[counter];
inFile >> testScores[counter];
counter++;
}
cout<<counter; //<-- tels me how many grades were read in.
cout << endl;
the problem I am having is that cout << counter is returning 2 when there are 10 grades to be read.
Line 2 is not needed.
counter should start from 0, not 1.
Because there are two consecutive reads of studentName[] the score (numeric value) gets stored in the name, then the program attempts to read a name (non-numeric) into the testScores[]. That will fail, and the loop terminates.
If I remove line 2 and start the counter at 0 won't that make the while(infile) return false and skip the loop all together?
as for the two consecutive reads of studentName[] ... I feel silly. Sometimes the problem is plain as day and you still can't see it. I changed the code to read the score in after the name and bingo. Thank you for your help. I would have spent half of the day and still wouldn't have figured it out. You are a lifesaver
So this isn't working for a whitespace-delimited input file?
1 2 3 4 5 6
int counter = 0;
while( (inFile >> studentName[counter]) && (inFile >> testScores[counter]) )
{
++counter;
}
cout << counter << endl; //<-- tels me how many grades were read in.
I think the suggestion from moorecm is better, not because it uses more or less code, but because the counter is incremented only when the data is successfully read from the file.