C++:如何检查 cin 缓冲区是否为空?

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

本文介绍了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 从键盘读取字符,直到用户按下回车键.例如:

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 Doename 的值将是 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 ... */
}

使用这种方法的缺点是,如果您想读取格式化的数据行、intdouble,您必须解析出表示的字符串.我个人认为这是值得的,因为它可以让您更精细地控制如果用户输入无效的内容并保护"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 缓冲区是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++:如何检查 cin 缓冲区是否为空?

基础教程推荐