4
What I want are a few statements that will clear an input stream of all characters currently in its buffer.

It seems like a super simple and reasonable task, but every solution I've ever gotten is either too complicated to understand, or doesn't work, or both.

I've tried using ignore(), but then if there's nothing in the input buffer, it waits for me to put something in for it to dispose of, until it's disposed of the exact number of characters I specified. getline() and cin.peek() work the same way, waiting for input if there isn't any yet. cin.sync() works to some degree, but it can't clear out endl characters; it gets stuck there.

I'd really like to be able to clear out multiple lines if necessary.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 3
    _"clear the input buffer of all characters"_ - for that to be possible, you need to know how big that buffer is and how many characters that are in it. Have you tried using a 3PP library like [tag:curses]? For some (mysterical) reason this kind of basic I/O part has been left out of the standard C++ library since ... forever. – Ted Lyngmo Feb 19 '22 at 23:48
  • 2
    Unrelated, but CLion isn't a compiler. It's an IDE that can be configured to use any of a number of compilers. You can check what compiler you're actually using under `Settings > Build, Execution, Deployment > Toolchains` – Brian61354270 Feb 20 '22 at 00:02
  • 1
    ISO C does not offer you this functionality. I believe it is the same for ISO C++. However, some platforms offer this functionality as a platform-specific extension. For example, on some platforms, it may be possible to accomplish this with [`fflush(stdin);`](https://stackoverflow.com/questions/2979209/using-fflushstdin) (although its behavior is undefined in ISO C). Also, [Microsoft's `rewind`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/rewind?view=msvc-170) function seems to allow this. If `std::cin` is synchronized to the C standard I/O functions, then it may work. – Andreas Wenzel Feb 20 '22 at 00:40
  • I think the question isn't unreasonable. I don't see it being possible using only standard C++ utilities though. – Ted Lyngmo Feb 20 '22 at 01:07

0 Answers0