Reading from an ifstream using a while loop

Hey guys just a quick question that has been bugging me with some of my code.

I've just been testing while loops with some of my code. The code that I'm writing now is pretty straight forward, it reads a line of data, stores in into c strings and does some stuff with the strings. But the while loop that I'm using seems to be going outside of the range of the array by 1 everytime.

Here is an example:

I have a text file which mightreads:

Student id: 328938 Score 34
Student id: 393924 Score 44

And then I use this fucntion to read in the data
1
2
3
4
5
6
7
8
9
10
11
12
13
	char studentid[2][9]; // 
	char studentanswers[2][21];

	int i = 0;
	while(testscore)
	{
	testscore.get(studentid[i], 9, ' ');
	testscore.ignore(256, ' ');
	testscore.get(studentanswers[i], 21, '\n');
	testscore.ignore(256, '\n');
	i++;
	}
}


Now say I've two lines of text written as shown above. The value of i will go to 3 and I'll get an error that the array has gone out of bounds.

Does anyone know hhow to get around this?

Thanks
Last edited on
If you know the number of students beforehand is 2, or know that your array can only hold 2 students, you can use while(i < 2). Otherwise, you can use vectors instead of arrays to store data.
You should also consider using getline() instead of get(), then you wouldn't need to worry about ignoring the delimiter. The getline() function extracts and discards that delimiter.

I would also recommend you use C++ strings instead of the C-strings, and vector instead of the array and use a structure to group the data instead of the discrete variables.

Topic archived. No new replies allowed.