Hi,

I'm having a little problem in my loop with the string array. I want to take a record for some student, but when I loop the function, the getline() did'nt work. It only work at the first loop, then it will skip it.

My code is like this

#include <iostream>
using namespace std;

int main()
{
	const int repeat = 3;
	string name[repeat];
	int age[repeat];

	for (int i = 0; i < repeat; i++)
	{
		cout << "Please enter the name of student " << i+1 << ": ";
		getline(cin, name[i]);
		cout << "Then the age of him/her: ";
		cin >> age[i];
	}


return 0;
}

The red one is the function that not work on the second loop and above and the output is like this.

Please enter the name of student 1: John
Then the age of him/her: 23
Please enter the name of student 2: Then the age of him/her: 21
Please enter the name of student 3: Then the age of him/her: 22

Can anybody figure it out?

When you enter an integer the program leaves the <Enter> key '\n' in the keyboard buffer so the next getline() will just extract it instead of waiting for more keyboard input. You need to flush that '\n' out of the keyboard buffer after the cin >> age[i]; One way to do that is: cin.flush(); There is a very extensive Read Me article at the top of this c++ forum that Narue wrote which explains in more detail how to flush the input stream.

When you enter an integer the program leaves the <Enter> key '\n' in the keyboard buffer so the next getline() will just extract it instead of waiting for more keyboard input. You need to flush that '\n' out of the keyboard buffer after the cin >> age[i]; One way to do that is: cin.flush(); There is a very extensive Read Me article at the top of this c++ forum that Narue wrote which explains in more detail how to flush the input stream.

Beat me to it!

Thanks man.. its very easy.. lol

just put

cin.ignore();

after the getline..

solve :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.