Isalpha () gives a statement

I have C code in which I use the standard isalpha () library function in ctype.h, this is on Visual Studio 2010-Windows. In the code below, if char c is '£', calling isalpha returns a statement, as shown in the screenshot below:

enter image description here

char c='£'; if(isalpha(c)) { printf ("character %c is alphabetic\n",c); } else { printf ("character %c is NOT alphabetic\n",c); } 

I see that this could be because 8-bit ASCII does not have this character.

So, how do I handle non-ASCII characters like this outside of an ASCII table?

What I want to do is if any non-alphabetic character is found (even if it contains such a character not in the 8-bit ASCII table), I want to be able to neglect it.

+7
source share
3 answers

You might want to pass the value sent to isalpha (and other functions declared in <ctype.h> ) to unsigned char

 isalpha((unsigned char)value) 

This is one of the (not so) cases when an actor is suitable for C.


Edited to add explanation.

In accordance with the standard , the focus is on

7.4

1 The heading <ctype.h> declares several functions useful for classifying and matching characters. In all cases, the argument is int , the value of which must be represented as unsigned char or equal to the value of the EOF macro. If the argument has any other value, the behavior is undefined.

Casting to unsigned char ensures that calling isalpha() does not call Undefined Behavior.

+8
source

You should pass int to isalpha() , not char . Pay attention to the standard prototype for this function:

 int isalpha(int c); 

Passing an 8-bit signed character will convert the value to a negative integer, which will result in an unlawful negative offset into the internal arrays commonly used by isxxxx() .

However, you must make sure that your char treated as unsigned when casting - you cannot just pass it directly to int , because if it is an 8-bit character, the resulting int will be negative.

A typical way to ensure this is to pass it to an unsigned char , and then rely on an implicit type conversion to convert it to int .

eg.

 char c = '£'; int a = isalpha((unsigned char) c); 
+8
source

You can compile with wchar (UNICODE) as a character type, in this case to use the iswalpha isalpha method

http://msdn.microsoft.com/en-us/library/xt82b8z8.aspx

+2
source

All Articles