#Ensure Input Buffer isn't empty before cin.ignore();

17 messages · Page 1 of 1 (latest)

quasi fossil
#

Is there an better Methode than this, to ensure the input buffer isn't empty before ignore everything in it?

auto input_buffer = std::cin.rdbuf();
input_buffer->sputbackc('\n')
std::cin.ignore(std::numeric_limitsstd::streamsize::max() ,'\n');

noble swiftBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

clear sparrow
#

this seems like an x-y-problem

noble swiftBOT
#
Beware the XY problem

The "XY problem" occurs when someone asks about an attempted solution rather than the problem itself. This makes it difficult to provide appropriate help and guide users to better solutions.

More info

quasi fossil
#

So is there a better Optiont?

clear sparrow
#

how are you using this?

#

by default, terminals are line-buffered

#

so by default, the buffer in std::cin will always either be empty or end with a newline

#

but you said you wanted to ignore everything in the input buffer, not just everything on the current line?

quasi fossil
#

I want to ignore everything in the Input buffer, to ensure, when calling std::getline(std::cin, input), my loop doesn't go through it twice. At the same time, when ignoring everything in the Input buffer and nothing is there, std::cin.ignore waits until something is in it. That's why I am pushing something to it to ensure it is not empty...

clear sparrow
#

you can use in_avail() to see if there are any characters available

#

but usually you should already know whether there's a newline character: when you're using >>, you don't consume a trailing newline, but when you're using getline you do

quasi fossil
#

It is for an Library, so I don't know if any input function was already called...

clear sparrow
#

if it's for a library, you might not want to hardcode std::cin

#

generally, you want to separate the part where you actually get the input as much as possible from the part where you deal with the input

#

so instead of having a function that reads from std::cin and then computes something with the input, you'd have the function take the input as a C++ type and make it the caller's responsibility to get the actual input