#include#include using namespace std; int main() { stringstream ss("5 abc"); int num; ss >> num; if (ss.fail()) { cout << "Error: Invalid Input.\n"; ss.clear(); } string str; ss >> str; cout << "Num: " << num << "\n"; cout << "Str: " << str << "\n"; return 0; }
#includeIn the above example, we are taking user input for a number and a string. If the user enters an invalid input (for example, enters a character instead of a number), the extraction operation will fail. We are checking for the error state of the stream using the fail() function and resetting the error using the clear() function. Additionally, we are ignoring any input data that has not been processed using the ignore() function. After that, we can take the user input for the string and print the output. Package/Library: iostreamusing namespace std; int main() { int num; string str; cout << "Enter a number: "; cin >> num; if (cin.fail()) { cout << "Error: Invalid Input.\n"; cin.clear(); cin.ignore(1000, '\n'); } cout << "Enter a string: "; getline(cin, str); cout << "Num: " << num << "\n"; cout << "Str: " << str << "\n"; return 0; }