Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Feb 11, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <iostream>
#include <string>
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;
  if ( ! error)
    // .. valid data entered; continue normally
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date