我正在使用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 anunsigned char
or shall equal the value of the macroEOF
. 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/