用户检测到的C ++检测ENTER键 [英] C++ Detecting ENTER key pressed by user
问题描述
我有一个循环,要求用户输入名称.当用户按ENTER键.....或输入20个名称时,我需要停止.但是,当用户按下ENTER键时,我的方法不会停止
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++;
}
推荐答案
您可以使用atoi
将读取的字符串转换为整数:
You convert the read string to an integer with atoi
:
int enterKey = atoi(temp.c_str());
如果temp是类似于"1234"
的字符串,这会将enterKey
设置为1234
.然后,将enterKey
与\n
的ASCII值进行比较.这很可能没有做任何有用的事情.
If temp is a string like "1234"
this will set enterKey
to 1234
. Then you compare enterKey
to the ASCII value of \n
. This is most probably not doing anything useful.
也std::getline
只是读取直到(但不包括)下一个'\n'
的字符.如果用户仅按Enter键而不输入任何其他字符,则std::getline
将返回一个空字符串.如果字符串为空,可以使用其empty()
方法轻松测试:
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 its empty()
method:
getline(cin, temp);
if (temp.empty()) {
stop = true;
}
这篇关于用户检测到的C ++检测ENTER键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!