views:

189

answers:

3

I have a section of code where the user enters input from the keyboard. I want to do something when ENTER is pressed. I am checking for '\n' but it's not working. How do you check if the user pressed the ENTER key?

if( shuffle == false ){
    int i=0;
    string line;
    while( i<20){
        cout << "Playing: ";
        songs[i]->printSong();
        cout << "Press ENTER to stop or play next song: ";
        getline(cin, line);            
        if( line.compare("\n") == 0 ){
            i++;
        }
    }
}
+2  A: 

getline returns only when an Enter (or Return, it can be marked either way depending on your keyboard) is hit, so there's no need to check further for that -- do you want to check something else, maybe, such as whether the user entered something else before the Enter?

Alex Martelli
oh you're right. thanks
+1  A: 

getline isn't going to return until enter is pressed. If you want to check if only entered was pressed, check if the line is empty: if (line.empty())

GMan
+2  A: 
if( shuffle == false ){
    int i=0;
    string line;
    while( i<20){
        cout << "Playing: ";
        songs[i]->printSong();
        cout << "Press ENTER to stop or play next song: ";
        if( cin.get() == '\n' ) {
            i++;
        }
    }
}
kurige
My understanding was that he is checking *only* for the newline character. And this is the best way to do just that.
kurige