2010-05-10 272 views
0

我有一个循环,我要求用户输入一个名称。当用户按下ENTER键时或当输入20个名字时,我需要停止。C++检测用户按下的ENTER键

while(!stop && ind < 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++; 


} 

回答

4

你读字符串转换为整数,atoi

int enterKey = atoi(temp.c_str());   

如果TEMP像"1234"这样的字符串将enterKey设置为1234。然后,您将enterKey\n的ASCII值进行比较。这很可能没有做任何有用的事情。

std::getline只读字符,但不包括,下一个'\n'。如果用户只按下输入而不键入任何其他字符,则std::getline将返回空字符串。如果字符串为空,可以用它empty()方法容易测试:

getline(cin, temp); 
if (temp.empty()) { 
    stop = true; 
} 
+0

你是对的。这工作 – user69514 2010-05-10 15:13:08

2

试试我的方法不停止

using namespace std; 
vector <string> names; // edited. 
for (int ind = 0; ind < 20; ++ind) 
{ 
    cout << "Enter name #" << (ind+1) << ":"; 
    string temp; 
    getline(cin, temp); 
    if (temp.empty()) 
     break; 
    names.push_back(temp); 
} 
+2

其实这是一个混乱。有几个错误... – 2010-05-10 14:50:07

+1

是的,我完全同意,'for'循环是要走的路。尽管你的代码有一个错误。结果向量将有20个空字符串,然后是一些响应。 – Geoff 2010-05-10 15:03:35

+0

你遗漏了atoi步骤。你应该使用一个向量而不是向量 jmucchiello 2010-05-10 15:06:49

2

函数getline会吃你的分隔符,这将是“\ n',所以你可能想要检查一个空字符串。在致电atoi之前做。

1

尝试用stop = temp.empty()代替。 getline不应该包含任何换行符。一个空行应该导致一个空字符串。

此外,查尔斯是正确的,你的条件不正确,使用while(!stop && ind < 20)。用户编写的方式需要输入20个值和一个空行。查尔斯的变化表明,只要符合任何一种条件(不是两种),就会突破。

为了完整起见,这里所提出的新代码:

bool stop = false; 
int ind = 0; 
while(!stop && ind < 20){ 

    cout << "Enter name #" << (ind+1) << ":"; 
    string temp; 
    getline(cin, temp); 
    if(temp.empty()) { 
     stop = true; 
    } else { 
     names[ind] = temp; 
    } 

    ind++;  
} 

就个人而言,我会写出如下代码:

vector<string> names; 
for(int ind = 0; ind < 20; ind++) { 
    cout << "Enter name #" << (ind + 1) << " (blank to stop): "; 
    string name; 
    getline(cin, name); 
    if(name.empty() || cin.eof()) { 
    break; 
    } 
    names.push_back(name); 
} 

cout << "Read " << names.length() << " names before empty line detected." << endl; 
+0

为什么不只是当temp.empty()时打破?那你就不需要其他结构啊 – jmucchiello 2010-05-10 15:03:42

+0

啊。是的。应该是<。我复制了它,错过了那里的错误。 – Geoff 2010-05-10 15:05:32

+0

你也忘了翻转ind> = 20的条件。 – jmucchiello 2010-05-10 15:05:57

0

你想用cin.get(); cin >> temp;我相信。

+0

cin >> temp'只会给一个令牌。 OP可能需要包含空格的语句。 – Geoff 2010-05-10 15:10:56