Possible Duplicate:
Need help with getline()
In the following code, my getline is skipped entirely and doesn't prompt for input.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
int main ()
{
int UserTicket[8];
int WinningNums[8];
char options;
string userName;
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto " << endl;
cout << "q) Quit Program " << endl;
cout << "Please make a selection: " << endl;
cin >> options;
switch (options)
{
case 'q':
return 0;
break;
case '1':
{
cout << "Please enter your name please: " << endl;
getline(cin, userName);
cout << userName;
}
cin.get();
return 0;
}
}
The problem is here:
You can only extract (
>>
) fromcin
when the user hits enter. So the user types 1 Enter and that line executes. Sinceoptions
is achar
, it extracts a single character (1
) fromcin
and stores it inoptions
. The Enter is still in the stdin buffer, since nothing has consumed it yet. When you get to thegetline
call, the first thing it sees in the buffer is the Enter, which marks the end of input, sogetline
immediately returns an empty string.There's lots of ways to fix it; probably the easiest way that fits with the model you're using in your program is to tell
cin
to ignore the next character in its buffer: