c - 将 char 转换为 int 作为 isspace 参数的惯用方法?

标签 c string char

我正在使用isspace为了迭代字符串并识别空白字符:

const char* s = "abcd efg";
const char* ptr = s;

for (; *ptr != '\0'; ptr++)
    printf("%c: %s\n", *ptr, isspace(*ptr) ? "yes" : "no");

如您所知,isspace需要 int ,不是char 。上面的内容似乎有效 - 但我想验证它是否是可移植的,或者“偶然工作”。

转换 char 的 idomatic 方法是什么?到int ,与 isspace 一起使用?

最佳答案

您应该使用unsigned char来管理角色。例如,fgetc返回一个“字符为 unsigned char转换为int ”(C 2018 7.21.7.1)。使用char可能会导致负值和未定义的行为,如下所述。

7.4 1 定义 <ctype.h> 的行为仅适用于其值可表示为 unsigned char 的参数的函数或EOF :

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.

因此,如果您有 char具有负值,并将其传递给 <ctype.h> 之一函数,该值不能表示为 unsigned char 。而且一般不是 EOF任何一个。负面char值将隐式转换为 int通过函数调用,但该值将保持负数。因此 C 标准不会定义该行为。

根据 6.2.5 3,基本执行字符集的所有成员都具有非负值:

If a member of the basic execution character set is stored in a char object, its value is guaranteed to be nonnegative.

按5.2.1 3、基本执行字符集至少包括大小写拉丁字母、十位数字、空格、水平制表符、垂直制表符、换页符、警报、退格键、回车符、换行符、和这些字符:

!"#%&’()*+,-./: ;?[\]^_{|}~

因此,如果您的字符串包含任何其他字符,则它可能具有负值。然后, <ctype.h> 的行为函数不是由 C 标准定义的。

关于c - 将 char 转换为 int 作为 isspace 参数的惯用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55799668/

相关文章:

c - 在 for 语句中声明变量时出错

c - 使用 C 语言的套接字编程,使用 select() 函数

ios - swift 3 - ios : convert anyObject to string

c# - 推导十进制数后面的所有字符,前导 0

c - stdarg.h 不处理字符指针

c - 在 while 循环中扫描字符

c++ - 如何使用 C++ 字符串将大写辅音替换为相应的小写辅音?

c - 如何获取结构体成员的地址

C 中静态内存分配与动态内存分配的成本

用于读取字符的 C 程序无法识别正确输入的字符串。