Easy way to check whether there is data pending in istream

Viewed 197

Is there any standard, non-reading way to check if there is any char pending in the input stream? I can always try something like

char buffer[256];
std::cin.get(buffer, 256, '\n');
if (!std::cin.fail()) {
// use buffer
}

but it condemns me to playing with ios flags, using C-strings and so forth. Isn't there any simpler, cleaner way to do it? Like this:

if (std::cin.has_data()) {
    std::string data;
    std::getline(std::cin, data);
    // do my stuff
} 
1 Answers

The function peek is the solution.

As said by the cppreference:

If good() == true, returns the next character as obtained by rdbuf()->sgetc()

Otherwise, returns Traits::eof().

Related