Suppose you have an application that reads input from the keyboard. How can you detect whether alphabetic data is being entered into an integer field from a cin statement?
The easiest way to validate the user’s input is by having cin read a string rather than a numeric data type such as int or float. After the user has entered the data, you should examine that string to detect its validity. For example:
#include #include using namespace std;int main(){ bool error = false; string data; cout<<"enter your age: "; // users must enter an integer cin>>data; // what if user enters a character by mistake? for (unsigned i = 0; i< data.length(); i++) // validate { if ( ! isdigit(data[i]) ) // any non-numeric values? { cout<< "illegal input"; error = true; break; } } if ( ! error) { // .. valid data entered; continue normally }}