#includeusing namespace std; int main() { int n; cin >> n; // User inputs "hello" if (cin.fail()) { cout << "Input failed!" << endl; cin.clear(); // Reset the fail bit cin.ignore(numeric_limits ::max(), '\n'); // Ignore the bad input } return 0; }
#includeThis example shows how to use the std::istream::fail() function to check if a file was successfully opened for input. If the open operation fails, we print an error message and exit the program. The std::istream::fail() function is part of the standard C++ library.using namespace std; int main() { ifstream fin("input.txt"); if (fin.fail()) { cout << "Failed to open file!" << endl; return 1; } // Read data from file fin.close(); return 0; }