Read file from second line

Hi, I have a file that contain data about student. File contain in this order
1.name of student
2.id
3.average

In the first line of the text I have a number that tell me how many entries are in the txt file.
Everything work good if I don't put this number at the beginning of the file. But, if it put it my program only display this number and not the student.

This is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void func(ifstream& file, ofstream& update)
{
	string name; int id; float average;
	int nbr;
	file >> nbr; cout << nbr;
	for (int i = 0; i < nbr; i++)
	{
		while (getline(file, name) && file >> id >> average)
		{
			cout << name << " " << id << " " <<average << endl;
			
			file.ignore(numeric_limits<streamsize>::max(), '\n');
		}
	}
}
Last edited on
>> leaves the trailing newline that the following getline() obtains as a blank line! Try

 
file >> nbr >> ws;


where ws consumes the white space following the number. You could also put the .ignore() line after the file>> statement.

Also instead of the .ignore(), you could use >> ws. Consider (not tried):

1
2
3
4
5
6
7
8
9
10
11
12
void func(ifstream& file, ofstream& update)
{
	string name;
	int id {};
	float average {};
	int nbr {};

	file >> nbr;

	for (int i = 0; (i < nbr) && getline(file >> ws, name) && (file >> id >> average); )
		cout << name << ' ' << id << ' ' << average << '\n';
}

Last edited on
Topic archived. No new replies allowed.