devxlogo

Validating Data Entries

Validating Data Entries

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  }}

See also  Monetize TikTok For Your Business
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist