我正在做一个小项目,需要比较流的第一个字节。问题在于该字节可以是 0xe5 或任何其他不可打印的字符,因此表示该特定数据是错误的(一次读取 32 位)。我可以允许的有效字符是 A-Z、a-z、0-9、'.'和空间。
当前代码为:
FILE* fileDescriptor; //assume this is already open and coming as an input to this function.
char entry[33];
if( fread(entry, sizeof(unsigned char), 32, fileDescriptor) != 32 )
{
return -1; //error occured
}
entry[32] = '\0'; //set the array to be a "true" cstring.
int firstByte = (int)entry[0];
if( firstByte == 0 ){
return -1; //the entire 32 bit chunk is empty.
}
if( (firstByte & 0xe5) == 229 ){ //denotes deleted.
return -1; //denotes deleted.
}
所以问题是当我尝试执行以下操作时:
if( firstByte >= 0 && firstByte <= 31 ){ //NULL to space in decimal ascii
return -1;
}
if( firstByte >= 33 && firstByte <= 45 ){ // ! to - in decimal ascii
return -1;
}
if( firstByte >= 58 && firstByte <= 64 ) { // : to @ in decimal ascii
return -1;
}
if( firstByte >= 91 && firstByte <= 96 ) { // [ to ` in decimal ascii
return -1;
}
if( firstByte >= 123 ){ // { and above in decimal ascii.
return -1;
}
这是行不通的。我看到一些字符,例如表示黑色六边形菱形的字符,里面有一个问号...理论上它应该只允许以下字符:Space (32), 0-9 (48-57 ), A-Z (65-90), a-z (97-122)
,但我不知道为什么它不能正常工作。
我什至尝试使用 ctype.h 中的函数 -> iscntrl、isalnum、ispunct,但这也没有用。
谁能帮助一个 c 新手解决我假设是一个简单的 c 问题?将不胜感激!
谢谢。 马丁
最佳答案
我不确定您为什么要将其转换为 int。考虑使用以下之一:
if ((entry[0] >= 'A' && entry[0] <= 'Z') ||
(entry[0] >= 'a' && entry[0] <= 'z') ||
entry[0] == ' ' || entry[0] == '.')
或
#include <ctype.h>
if (isalnum(entry[0]) || entry[0] == ' ' || entry[0] == '.')
关于c - 如何比较c中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5785519/