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.
/*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>
usingnamespace 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.