std::ifstream input_file("example.txt"); if (input_file.bad()) { std::cerr << "Error opening file!" << std::endl; return 1; } // continue processing the file...
std::string line; while (std::getline(std::cin, line)) { if (std::cin.bad()) { std::cerr << "Error reading input!" << std::endl; return 1; } // process the input... }In this example, we read input from the standard input using std::getline, and check if there was any error reading it. If std::cin.bad() returns true, we print an error message and exit the program. The std::istream bad function is part of the C++ Standard Library.