problems with getLine() function

I can't figure out why this isn't working, please help. I'm trying to use the getLine() function to have the user enter the command "read note" to read the note1 string. Here is a small section of my program where I believe the problem is:

1
2
3
4
5
6
7
8
while(true){
        cout << "\nWhat do you want to do? "  << endl;
        getline(cin,choice);
        if(choice == "read note"){
            cout << "The note reads: \"" << note1 << "\"";
        break;
        }else cout << "Invalid Entry.  Commands are: read, move\n";
}


For some reason, when I run the code it says "Invalid Entry. Commands are: read, move" before I type anything. It allows me to enter the next time though. Please help me fix this problem.
Are you doing cin >> something; a few lines before this?

If so, the >> is leaving the linebreak character in the buffer which causes getline to return an empty string.

I explain this in more detail (and provide a solution) here:

http://www.cplusplus.com/forum/beginner/121955/#msg664472
1
2
3
4
5
6
7
8
9
10
11
while(true){
        cout << "\nWhat do you want to do? "  << endl;

        // getline(cin,choice);
        getline( cin >> ws, choice ) ;

        if(choice == "read note"){
            cout << "The note reads: \"" << note1 << "\"";
        break;
        }else cout << "Invalid Entry.  Commands are: read, move\n";
}


std::getline( input_stream >> std::ws, string ) is canonical, when we mix formatted/unformatted input.
What you said worked Disch, but now that I added more commands that don't break from the loop, the getLine is returning nothing after one of those commands even with the cin.ignore(100, '\n') which is in that loop.
Last edited on
Topic archived. No new replies allowed.