devxlogo

Detecting Alphabetic Data

Detecting Alphabetic Data

Question:
How do you detect alphabetic data being entered into an integer field from a cin statement?

Answer:
The easiest way to do that is by having cin read a string rather than an int. Then you can examine the string to detect its validity. For example:

#include #include using std::string;using std::cout;using std::cin;int main(){  bool error = false;  string data;  cout<<"enter your age: ";  cin>>data;  for (unsigned int i = 0; i< data.length(); i++)  {    if ( ! isdigit(data[i]) )    {     cout<< "illegal input";     error = true;     break;    }  // continue normally  }}

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