为什么getline不会产生我预期的文字?

时间:2011-05-10 16:54:15

标签: c++ getline

  

可能重复:
  Need help with 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;
    }
}

1 个答案:

答案 0 :(得分:9)

问题在于:

cin >> options;

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

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

cin >> options;
cin.ignore();