Search code examples
c++user-inputgetline

C++ Detecting ENTER key pressed by user


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


}

Solution

  • You convert the read string to an integer with atoi:

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

    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.

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