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++;
}
You convert the read string to an integer with
atoi:If temp is a string like
"1234"this will setenterKeyto1234. Then you compareenterKeyto the ASCII value of\n. This is most probably not doing anything useful.Also
std::getlinejust read the characters up to, but not including, the next'\n'. If a user just presses enter without typing any other characters,std::getlinewill return an empty string. If a string is empty can be easily tested with itsempty()method: