getline(cin, n) issue

I took a beginner's C++ course over a year ago, and I'm just going through the book freshening up on some problems.

In the code, when I replace "cin >> input" with "getline(cin, input)" I'm running into a double prompt of "Enter the name of the student: " as well as other errors, like missing the the first letter of a name and the program not working right. Is it because I have it in a do while loop? Could I use a different style of loop? The program "works" as instructed if i just leave "cin >> input" there... but I was wondering if I wanted to add a last name, just because.

The exact problem description is in the top of the code.

In this section of the book, sorting algorithms nor arrays have been introduced yet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*Chapter 5 Problem 13
A teacher has asked all her students to line up single file according to their first name. For
example, in one class Amy will be at the front of the line and Yolanda will be at the end.
Write a program that prompts the user to enter the number of students in the class, then
loops to read in that many names. Once all the names have been read in it reports which
student would be at the front of the line and which one would be at the end of the line.
You may assume that no two students have the same name.
Input Validation: Do not accept a number less than 1 or greater than 25 for the number
of students.*/

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string large, small, input;
	int numOfStudents;
	int i = 1;

	do
	{
		cout << "\n\nEnter number of student names to input: ";
		cin  >> numOfStudents;

		if (numOfStudents < 1 || numOfStudents > 25)
		{
			cout << "\nPlease input a number between 1 and 25.";
		}

	} while (numOfStudents < 1 || numOfStudents > 25);

	do
	{
		cout << "\nEnter the name of the student: ";
		cin  >> input;

		if (i == 1)
		{
			small = large = input;
		}

		else
		{
			if (input < small)
			{
				small = input;
			}

			if (input > large)
			{
				large = input;
			}
		}

		i++;

	} while (i <= numOfStudents);

	cout << "\nThe first person in line is " << small << ".\n"
		 << "The last person in line is " << large << ".\n\n";

	return 0;
}
getline() and formatted input such as cin >> numOfStudents; don't always play nicely together. The reason is that the input buffer will still have at the very least a trailing newline '\n' after the user has entered the number of students. You need to clear that out, just once, after the end of the first loop.

Try inserting this at line 33 in your code:
 
    cin.ignore(1000, '\n');


http://www.cplusplus.com/reference/istream/istream/ignore/
OK, thanks. I had forgot about that.
Topic archived. No new replies allowed.