I'm writing a terminal application and I want to pause the program at certain points and wait for the user before continuing. I want to avoid OS dependent code so I'm not using Press any key to continue . . .
, see this answer. I decided the next best thing is Press enter to continue . . .
, but I can't seam to make that work reliably.
I've tried the following methods to pause for the user to input a newline character to no avail.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')`;
std::string foo;
getline(std::cin, foo);
char foo{0};
std::cin >> std::noskipws;
while(foo != '\n') {
std::cin >> foo;
}
std::cin >> std::skipws;
The problem is that I'm getting user input using std::basic_istream& operator>>(int)
or std::basic_istream& operator>>(char)
which leaves trailing whitespace. So if I receive input before calling my puaseForEnter()
function then it doesn't pause, but if I call pauseForEnter()
twice in a row, with some output in between, it works fine. Doubling up the code for pausing results in sometimes requiring the user to push enter twice.
I believe that detecting any other character would have the same issue.
I looked for a method to clear the stream (consume all characters currently in the stream) without causing it to pause, but I didn't see any. Is there another way to accomplish what I want?