#includeint main() { std::istream input{std::cin.rdbuf()}; int value; // try to read an integer from standard input input >> value; // check if the input operation was successful if (input.eof()) { std::cout << "End of input" << std::endl; } else if (input.fail()) { std::cout << "Input error" << std::endl; input.clear(input.rdstate() & ~std::ios::failbit); } else { std::cout << "Read value: " << value << std::endl; } return 0; }
#includeIn this example, we create an input stream object from a string stream and set the skipws flag so that any leading whitespace characters are skipped before reading the next value from the stream. We then read a string from the stream and check if the read operation was successful. If it failed due to an input error, we clear the failbit state so that we can reattempt the read operation. Both of these examples use the std::istream setstate function to modify the state flags of an input stream object, which is part of the#include int main() { std::istringstream input{"foo bar baz"}; // skip whitespace characters before reading the next value input >> std::skipws; // read a string value from the input stream std::string value; input >> value; // check if the input operation was successful if (input.eof()) { std::cout << "End of input" << std::endl; } else if (input.fail()) { std::cout << "Input error" << std::endl; input.clear(input.rdstate() & ~std::ios::failbit); } else { std::cout << "Read value: " << value << std::endl; } return 0; }