getline(cin,string)不工作EVEN WITH cin.ignore() [英] getline(cin, string) not working EVEN WITH cin.ignore()

查看:184
本文介绍了getline(cin,string)不工作EVEN WITH cin.ignore()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个网站上有几个问题,指的是 getline 不工作,显而易见的解决方案是缓冲区中有剩余的换行字符需要清除,据称 cin.ignore()。我试过这么多变化这个,没有什么似乎工作,我想做的只是简单的控制台输入和 cin>> string

There are several questions on this site referring to getline not working, the apparent solution is that there are remaining newline characters in the buffer that need to be cleared, supposedly with cin.ignore(). I've tried so many variations of this and nothing seems to work, all I'm trying to do is simple console input and cin >> string isn't an option because the string might have spaces.

这是我的代码。

void prompt(std::string * str)
{
    cout << "> ";

    cin.sync();
    cin.get();
    cin.ignore(256, '\r');
    cin.ignore(256, '\n');
    cin.ignore();
    cin.ignore();

    std::string tmp;
    getline(cin, tmp);

    cin.sync();
    cin.get();
    cin.ignore(256, '\r');
    cin.ignore(256, '\n');

    *str = tmp;
}

正如你所看到的,我已经尝试过各种各样的事情。它仍然跳过 getline(cin,tmp),并显示为将 str 设置为空字符串。请帮忙。感谢您的时间。

As you can see I've tried all sorts of things. It still skips right over getline(cin,tmp) and appears to set str to an empty string. Please help. Thank you for your time.

推荐答案

一旦格式化的提取失败,failbit就会在您的流上设置,什么都不做。这有点方便,因为您可以处理组中的错误,而不是每次单个操作后检查。但是一旦你检测到错误,你需要重置failbit为了尝试不同的东西。这样做的命令很简单:

Once any formatted extraction has failed, the failbit will be set on your stream, and future operations will do nothing at all. This is somewhat convenient because you can handle errors in groups, instead of checking after every single operation. But once you detect an error, you need to reset the failbit in order to try something different. The command to do that is pretty simple:

cin.reset();

这篇关于getline(cin,string)不工作EVEN WITH cin.ignore()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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