isalpha() giving an assertion

会有一股神秘感。 提交于 2019-11-27 05:27:38

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

isalpha((unsigned char)value)

It's one of the (not so) few occasions where a cast is appropriate in C.


Edited to add an explanation.

According to the standard, emphasis is mine

7.4

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

The cast to unsigned char ensures calling isalpha() does not invoke Undefined Behaviour.

You must pass an int to isalpha(), not a char. Note the standard prototype for this function:

int isalpha(int c);

Passing an 8-bit signed character will cause the value to be converted into a negative integer, resulting in an illegal negative offset into the internal arrays typically used by isxxxx().

However you must ensure that your char is treated as unsigned when casting - you can't simply cast it directly to an int, because if it's an 8-bit character the resulting int would still be negative.

The typical way to ensure this works is to cast it to an unsigned char, and then rely on implicit type conversion to convert that into an int.

e.g.

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

You may be compiling using wchar (UNICODE) as character type, in that case the isalpha method to use is iswalpha

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!