0

可能重复:
在 getline() 方面需要帮助

在下面的代码中,我的 getline 被完全跳过并且不提示输入。

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

1 回答 1

9

问题在这里:

cin >> options;

您只能在用户按 Enter 时提取 ( >>) 。cin因此,用户键入1 Enter并执行该行。由于options是 a char,它从 中提取单个字符 ( 1)cin并将其存储在options. Enter仍然在标准输入缓冲区中,因为还没有消耗它。当你开始getline调用时,它在缓冲区中看到的第一件事是Enter,它标志着输入的结束,因此getline立即返回一个空字符串。

有很多方法可以解决它;可能适合您在程序中使用的模型的最简单方法是告诉cin忽略其缓冲区中的下一个字符:

cin >> options;
cin.ignore();
于 2011-05-10T17:00:54.443 回答