Why does getline not result in the text I expected

2019-03-05 06:08发布

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;
    }
}

标签: c++ getline
1条回答
Emotional °昔
2楼-- · 2019-03-05 06:44

The problem is here:

cin >> options;

You can only extract (>>) from cin when the user hits enter. So the user types 1 Enter and that line executes. Since options is a char, it extracts a single character (1) from cin and stores it in options. The Enter is still in the stdin buffer, since nothing has consumed it yet. When you get to the getline call, the first thing it sees in the buffer is the Enter, which marks the end of input, so getline 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:

cin >> options;
cin.ignore();
查看更多
登录 后发表回答