0

我有一个循环,要求用户输入名称。当用户按下 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++;


}
4

5 回答 5

4

您将读取的字符串转换为整数atoi

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

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

std::getline只需阅读字符直到但不包括下一个'\n'。如果用户只是按下回车键而不输入任何其他字符,std::getline将返回一个空字符串。如果字符串为空,可以使用它的empty()方法轻松测试:

getline(cin, temp);
if (temp.empty()) {
  stop = true;
}
于 2010-05-10T14:52:31.680 回答
2

尝试:

while( !stop && ind < 20 )

或者:

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);
}
于 2010-05-10T14:46:21.000 回答
2

getline 会吃掉你的分隔符,这将是'\ n',所以你可能想要检查一个空字符串。在调用 atoi 之前执行此操作。

于 2010-05-10T14:50:37.497 回答
1

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:

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++;    
}

Personally, I would write the code as follows:

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;
于 2010-05-10T14:52:06.807 回答
0

你想使用 cin.get(); 辛 >> 温度; 我相信。

于 2010-05-10T15:08:45.103 回答