Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Feb 14, 2000

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
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

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