C ++:如何检查cin缓冲区是否为空? [英] C++: how do I check if the cin buffer is empty?

查看:541
本文介绍了C ++:如何检查cin缓冲区是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查用户是否未在cin命令上输入任何内容,而只是按Enter键?

How do you check to see if the user didn't input anything at a cin command and simply pressed enter?

推荐答案

std :: cin 阅读时,最好不要使用流提取运算符 >> ,因为这可能会带来各种令人讨厌的副作用。例如,如果您具有以下代码:

When reading from std::cin, it's preferable not to use the stream extraction operator >> as this can have all sorts of nasty side effects. For example, if you have this code:

std::string name;
std::cin >> name;

然后输入 John Doe ,然后输入从 cin 读取的行将仅保留值 John ,而留下 Doe 后面供将来的某些读取操作读取。同样,如果我要写:

And I enter John Doe, then the line to read from cin will just hold the value John, leaving Doe behind to be read by some future read operation. Similarly, if I were to write:

int myInteger;
std::cin >> myInteger;

然后我输入 John Doe ,那么 cin 将进入错误状态,并拒绝进行任何后续的读取操作,直到您明确清除其错误状态并清除导致错误的字符为止。

And I then type in John Doe, then cin will enter an error state and will refuse to do any future read operations until you explicitly clear its error state and flush the characters that caused the error.

一种更好的用户输入方法是使用 std :: getline 从键盘读取字符,直到用户按下Enter键为止。例如:

A better way to do user input is to use std::getline to read characters from the keyboard until the user hits enter. For example:

std::string name;
getline(std::cin, name); // getline doesn't need the std:: prefix here because C++ has ADL.

ADL 代表与参数相关的查找。现在,如果我输入 John Doe ,则 name 的值将为 John Doe cin 中将没有任何数据。而且,这还可以让您测试用户是否刚刚按下Enter键。

ADL stands for argument-dependent lookup. Now, if I enter John Doe, the value of name will be John Doe and there won't be any data left around in cin. Moreover, this also lets you test if the user just hit enter:

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

if (name.empty()) {
    /* ... nothing entered ... */
}

使用此方法的缺点是,如果要在格式化的数据行中读取,则 int double ,则必须从字符串中解析表示形式。我个人认为这是值得的,因为它可以让您更好地控制如果用户输入无效内容并防止 cin 进入失败的情况该怎么办。

The drawback of using this approach is that if you want to read in a formatted data line, an int or a double you'll have to parse the representation out of the string. I personally think this is worth it because it gives you a more fine-grained control of what to do if the user enters something invalid and "guards" cin from ever entering a fail state.

我教C ++编程课程,并且有关流库的一些讲义,其中详细介绍了如何从 cin 中读取格式化数据一种安全的方法(通常在本章的最后)。我不确定您会发现它有多有用,但是如果有帮助的话,我想我应该发布链接了。

I teach a C++ programming course, and have some lecture notes about the streams library that goes into a fair amount of detail about how to read formatted data from cin in a safe way (mostly at the end of the chapter). I'm not sure how useful you'll find this, but in case it's helpful I thought I'd post the link.

希望这会有所帮助!

这篇关于C ++:如何检查cin缓冲区是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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