在 C++ 中检测 ENTER 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42818899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting ENTER key in C++
提问by Arturo Aguilera
I have a program like this,
我有一个这样的程序
char name[100];
char age[12];
cout << "Enter Name: ";
cin >> name;
cout << "Enter Age: ";
cin >> age;
Now age is a optional field, so user can simply press ENTER key and have that value as NULL. But the problem is, cin doesn't take ENTER key and just stay there waiting for a valid keyboard char or numerical input.
现在年龄是一个可选字段,因此用户只需按 ENTER 键并将该值设为 NULL。但问题是,cin 不接受 ENTER 键,只是在那里等待有效的键盘字符或数字输入。
I think the problem is because cin needs a valid input and thus stays there forever.
我认为问题是因为 cin 需要一个有效的输入,因此永远留在那里。
So i tried below approach to detect ENTER key press for Age.
所以我尝试了以下方法来检测年龄的 ENTER 按键。
cout << "Enter Age: ";
if (cin.get() == '\n') {
cout << "ENTER WAS PRESSED" << endl;
}
Now as soon as user presses ENTER key after entering a NAME, it goes straight to the IF condition.
现在,只要用户在输入 NAME 后按下 ENTER 键,它就会直接进入 IF 条件。
I also tried:
我也试过:
getline(cin, age);
But that also simply doesn't stop at cout << "Age: ";
waiting for an input from the user.
但这也不仅仅停留在cout << "Age: ";
等待用户输入。
The user can either a valid age or simply press ENTER key not to enter a age.
用户可以输入有效年龄,也可以直接按 ENTER 键不输入年龄。
For the below Code:
对于以下代码:
cout << "Enter Name: ";
cin >> name;
cout << "Enter Age: ";
if (cin.get() == '\n') {
cout << "ENTER WAS PRESSED" << endl;
}
The Output is:
输出是:
Enter Name: asdf
Enter Age: ENTER WAS PRESSED
I want the cursor to wait at Enter Age: _
我希望光标在Enter Age等待:_
How can i do that?
我怎样才能做到这一点?
回答by Arturo Aguilera
Have you tried this?:
你试过这个吗?:
cout << "Press Enter to Continue";
cin.ignore();
also check out this question
也看看这个问题
回答by Remy Lebeau
You are several problems with your code:
你的代码有几个问题:
you are calling
operator>>
withchar[]
buffers without protection from buffer overflows. Usestd::setw()
to specify the buffer sizes during reading. Otherwise, usestd::string
instead ofchar[]
.cin >> name
reads only the first whitespace-delimited word, leaving any remaining data in the input buffer, including the ENTERkey, which is then picked up bycin >> age
without waiting for new input. To avoid that, you need to callcin.ignore()
to discard any unread data. Otherwise, consider usingcin.getline()
instead (orstd::getline()
forstd::string
), which consumes everything up to and including a linebreak, but does not output the linebreak (you should consider using this for thename
value, at least, so that users can enter names with spaces in them).by default,
operator>>
skips leading whitespace before reading a new value, and that includes line breaks. You can press ENTERall you want,operator>>
will happily keep waiting until something else is entered. To avoid that, you could usestd::noskipws
, but that causes an unwanted side effect when reading character data - leading whitespace is left in the input buffer, which causesoperator>>
to stop reading when it reads a whitespace character before any user input is read. So, to avoid that, you can usecin.peek()
to check for an entered linebreak before callingcin >> age
.
您正在
operator>>
使用char[]
缓冲区调用而没有缓冲区溢出保护。利用std::setw()
读书期间指定缓冲区的大小。否则,使用std::string
代替char[]
。cin >> name
仅读取第一个以空格分隔的单词,将任何剩余数据留在输入缓冲区中,包括ENTERkey,然后cin >> age
无需等待新输入即可拾取。为避免这种情况,您需要调用cin.ignore()
以丢弃任何未读数据。否则,请考虑使用cin.getline()
替代(或std::getline()
forstd::string
),它消耗包括换行符在内的所有内容,但不输出换行符(您应该考虑将其用于name
值,至少,以便用户可以输入带有空格的名称) .默认情况下,
operator>>
在读取新值之前跳过前导空格,包括换行符。你可以按ENTER你想要的所有东西,operator>>
会很高兴地继续等待,直到输入其他东西。为避免这种情况,您可以使用std::noskipws
, 但这会导致在读取字符数据时产生不必要的副作用 - 输入缓冲区中保留了前导空白,这会导致operator>>
在读取任何用户输入之前读取空白字符时停止读取。因此,为了避免这种情况,您可以cin.peek()
在调用cin >> age
.
Try something more like this:
尝试更像这样的事情:
#include <iostream>
#include <limits>
#include <iomanip>
char name[100] = {0};
char age[12] = {0};
std::cout << "Enter Name: ";
std::cin >> std::setw(100) >> name;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
if (!std::cin.getline(name, 100))
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
*/
std::cout << "Enter Age: ";
if (std::cin.peek() != '\n')
std::cin >> std::setw(12) >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Or:
或者:
#include <iostream>
#include <string>
#include <limits>
std::string name;
std::string age;
std::cout << "Enter Name: ";
std::cin >> name;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
std::getline(std::cin, name);
*/
std::cout << "Enter Age: ";
if (std::cin.peek() != '\n')
std::cin >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
std::getline(std::cin, age);
*/
回答by Xiokraze
One way to do it is to use getline to read the input, then test the length of the input string. If they only press enter, the length of the line will be 0 since getline ignores newlines by default.
一种方法是使用 getline 读取输入,然后测试输入字符串的长度。如果他们只按回车键,则行的长度将为 0,因为默认情况下 getline 会忽略换行符。
std::string myString = "";
do {
std::cout << "Press ENTER to exit" << std::endl;
std::getline(std::cin, myString);
} while (myString.length() != 0);
std::cout << "Loop exited." << std::endl;
回答by TechBot
you can include the "conio.h" library and use getch();
您可以包含“conio.h”库并使用 getch();
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
cout << "press enter";
getch();
return 0;
}
回答by Brain
Just use:
只需使用:
std::cout << "\nPress Enter to continue";
fgetc(stdin);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
See more at http://www.cplusplus.com/reference/cstdio/fgetc/
回答by Meccano
You might want to cin into a char variable and then check if it the ENTER key, and if not, continue getting characters and turn them into an int (using character substraction and all that). It is not a very pretty solution but it is the first thing that came into my head.
您可能希望将 cin 转换为 char 变量,然后检查它是否按 ENTER 键,如果不是,则继续获取字符并将它们转换为 int(使用字符减法等)。这不是一个非常漂亮的解决方案,但这是我想到的第一件事。