C++检测用户按下 ENTER 键
我有一个循环,要求用户输入名称。当用户按下 ENTER 键或输入 20 个名称时,我需要停止。但是,当用户按 ENTER 键时,我的方法不会停止
//loop until ENTER key is entered or 20 elements have been added
bool stop = false;
int ind = 0;
while( !stop || ind >= 20 ){
cout << "Enter name #" << (ind+1) << ":";
string temp;
getline(cin, temp);
int enterKey = atoi(temp.c_str());
if(enterKey == '\n'){
stop = true;
}
else{
names[ind] = temp;
}
ind++;
}
I have a loop where I ask the user to enter a name. I need to stop when the user presses the ENTER key..... or when 20 names have been entered. However my method doesn't stop when the user presses the ENTER key
//loop until ENTER key is entered or 20 elements have been added
bool stop = false;
int ind = 0;
while( !stop || ind >= 20 ){
cout << "Enter name #" << (ind+1) << ":";
string temp;
getline(cin, temp);
int enterKey = atoi(temp.c_str());
if(enterKey == '\n'){
stop = true;
}
else{
names[ind] = temp;
}
ind++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
atoi
将读取的字符串转换为整数:如果 temp 是类似
"1234"
的字符串,则会将enterKey
设置为1234
。然后将enterKey
与\n
的 ASCII 值进行比较。这很可能没有做任何有用的事情。另外,
std::getline
仅读取字符,但不包括下一个'\n'
。如果用户只按 Enter 键而不输入任何其他字符,std::getline 将返回空字符串。可以使用其empty()
方法轻松测试字符串是否为空:You convert the read string to an integer with
atoi
:If temp is a string like
"1234"
this will setenterKey
to1234
. Then you compareenterKey
to the ASCII value of\n
. This is most probably not doing anything useful.Also
std::getline
just read the characters up to, but not including, the next'\n'
. If a user just presses enter without typing any other characters,std::getline
will return an empty string. If a string is empty can be easily tested with itsempty()
method:getline 会吃掉您的分隔符,即“\n”,因此您可能需要检查空字符串。在调用 atoi 之前执行此操作。
getline will eat your delimiter, which will be '\n', so you probably want to be checking for an empty string. Do it before the call to atoi.
尝试:
或:
try:
or:
尝试使用
stop = temp.empty()
来代替。getline
不应包含任何换行符。空行应该产生空字符串。另外,查尔斯是正确的,您的 while 条件不正确,请使用
while(!stop && ind <20)
。按照您编写的方式,用户需要输入 20 个值和一个空行。查尔斯的更改表示,当满足其中一个条件(而不是同时满足两个条件)时就中断。为了完整起见,这里是建议的新代码:
就我个人而言,我会编写如下代码:
Try
stop = temp.empty()
instead.getline
should not contain any new-line characters. An empty line should result in an empty string.Also, Charles is correct, your while condition is incorrect, use
while( !stop && ind < 20)
. The way you have it written the user needs to enter 20 values, and an empty line. Charles' change says to break when either condition is met (not both).For the sake of completeness, here's the proposed new code:
Personally, I would write the code as follows:
您想使用 cin.get();辛>>温度;我确实相信。
You want to use cin.get(); cin >> temp; I do believe.