为什么getline无法产生我期望的文本? [英] Why does getline not result in the text I expected?

查看:62
本文介绍了为什么getline无法产生我期望的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
Need help with getline()

在以下代码中,我的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;
    }
}

推荐答案

问题在这里:

cin >> options;

仅当用户按下Enter键时,才能从cin中提取(>>).因此,用户键入 1 Enter ,然后执行该行.由于optionschar,因此它将从cin中提取单个字符(1)并将其存储在options中. Enter 仍在stdin缓冲区中,因为尚未消耗掉它.进入getline调用时,它在缓冲区中首先看到的是 Enter ,它标志着输入的结束,因此getline立即返回一个空字符串.

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.

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

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();

这篇关于为什么getline无法产生我期望的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆