Getline Issue!

I am having an issue using getline in my for loop. when I use cin the program runs fine. to clarify instead of using cin >> student; I want to use getline(cin, student);

what happens with the code as below is first I enter number of grades. then I enter student name. then their score and the loop repeats the correct number of times and spits out the average.

however when I try to substitute the getline in there, the program will ask me for number of grades and when I press enter, it prints out "Enter student name: Enter grade between 0-100: " all on the same line without the ability to actually enter the string for the students name.

What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  cout << "How many grades would you like to enter?: ";
	cin >> score;
		
		for(int z = 0; z < score; z++)
		{
			
			// get score between 0-100
			cout << "Enter student's name: ";
			cin >> student;
			
			

			cout << "Enter a grade between 0-100: ";
			cin >> grade;
			sum += grade;
Last edited on
I read through that question on stack. Thanks for the link. I see there is a few methods for this, however I haven't the slightest idea where to implement them as it relates to my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cout << "How many grades would you like to enter?: ";
	cin >> score;
		
		for(int z = 0; z < score; z++)
		{
			
			// get score between 0-100
			cout << "Enter student's name: ";
			getline(cin, student);
			
			

			cout << "Enter a grade between 0-100: ";
			cin >> grade;
			sum += grade;

	

			// if less than 0 and greater than 100 terminate 


where are these solutions supposed to be placed so I can try them out?
1
2
3
4
5
6
for(int z = 0; z < score; z++)
		{
			cin.ignore();
			// get score between 0-100
			cout << "Enter student's name: ";
			getline(cin, student);


When you switch from cin to getline. So the best place would be at teh top of the forloop, because first you use a cin, then the ignore, then getline and then cin, then the ignore etc.
That did it, Thank you for the help. Hey, just out of curiosity, If I had more cin's followed by getlines in my forloop, would this cin.ignore at the top prevent this issue permanently, or could it happen again? If so would I just put cin.ignore directly before the getline where I was having the issue?
Topic archived. No new replies allowed.