#includeusing namespace std; int main() { int num; cout << "Enter a number: "; // Read the input from the user cin >> num; // Check if the input stream is valid or not if (cin.good()) { cout << "Number entered is: " << num << endl; } else { cerr << "Invalid input! Please enter valid data." << endl; } return 0; }
#includeIn this example, we are reading data from a file and then checking the validity of the input stream using the istream good function. If the input is valid, it will print the number read from the file; otherwise, it will print an error message. Package/library: The fstream library is a part of the C++ Standard Library.#include using namespace std; int main() { int num; ifstream infile("data.txt"); // Read the input from the file infile >> num; // Check if the input stream is valid or not if (infile.good()) { cout << "Number read from the file is: " << num << endl; } else { cerr << "Error reading data from the file." << endl; } return 0; }