Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ problems involving getline() and a loop

Tags:

c++

I am working an a school assignment and am beating my head against a wall right now trying to figure out why my program is not behaving as I'd like it to!

int main(){
    string input;
    char choice;

    bool getChoice(char);
    string getInput();

    CharConverter newInput; 

    do{
        cout << "Please enter a sentence.\n";
        getline(cin, input);

        cout << newInput.properWords(input) << endl;

        cout << newInput.uppercase(input) << endl;
        cout << "Would you like to do that again?\n";
        cin >> choice;



    } while (getChoice(choice) == true);

    return 0;
}

This program works fine on the first round, but I am having a problem when getChoice() == true, and the do while block is looped a second time. On the second loop, the program asks for me to enter a sentence again, but then just jumps to "Would you like to do that again?" without allowing user input or outputting the results of the properWords() and uppercase() functions. I suspect that there is something about getline that I do not understand, but I have yet to find it through my googling. Any help out there?

edit: there was a mistake in my original explanation.

like image 459
user3468711 Avatar asked Nov 07 '14 16:11

user3468711


1 Answers

This is because reading input with getline does not mix well with reading input character-by-character. When you enter the Y/N character to indicate if you want to proceed or not, you also press Enter. This puts \n in the input buffer, but >> does not take it from there. When you call getline, the \n is right there, so the function returns an empty string right away.

To fix this, make choice a std::string, use getline to read it, and send the first character to getChoice function, like this:

string choice;
...
do {
    ...
    do {
        getline(cin, choice);
    } while (choice.size() == 0);
} while (getChoice(choice[0]));
like image 50
Sergey Kalinichenko Avatar answered Sep 29 '22 21:09

Sergey Kalinichenko