Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Sep 15, 2000



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

Overcoming a Common Bug in

The standard functions isalpha(), isdigit(), isprint() etc., defined in the standard header or often fail to produce the right results because they assume that their arguments are of type 'unsigned char'. On certain implementations, char is signed by default and this causes ctype functions to fail. For efficiency reasons, most implementations use bitwise operators rather than relational operators to implement these functions. The problem is that bitwise operations work well only when applied to unsigned values. What can you do to fix this problem? Explicitly cast the arguments of these functions to unsigned char. This will ensure that the ctype functions produce the correct results, whether their arguments are unsigned or not:


char c;
cout << "enter a character";
cin >> c;
bool alpha = isalpha ( (unsigned char) c); // explicit cast
if (!alpha)
  cout << "invalid character entered";
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