C ++ issues using getline () and loop

I work in a school assignment and now I bang my head against the wall, trying to understand why my program does not behave the way I would like!

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 in the first round, but I have a problem when getChoice () == true, and the second is the second. In the second cycle, the program asks me to re-enter the sentence, but then just jumps to "Do you want to do this again?" without user input or output of the correct word () and uppercase () functions. I suspect there is something about getline that I don’t understand, but I have yet to find it in my search. Any help there?

edit: An error occurred in my original explanation.

+5
source share
1 answer

This is due to the fact that reading input with getline does not mix well with reading input by character. When you type Y / N to indicate whether you want to continue or not, you also press Enter . This puts \n in the input buffer, but >> does not take it from there. When you call getline , \n , so the function immediately returns an empty string.

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

 string choice; ... do { ... do { getline(cin, choice); } while (choice.size() == 0); } while (getChoice(choice[0])); 
+5
source

Source: https://habr.com/ru/post/1206440/


All Articles