我正在阅读我的字典,并打印出单词+单词的长度,以供测试之用。
我用strlen来得到字符串的长度。然而,我得到的数字是不正确的。我相信斯特伦不算\0这个角色。
我正在读字典里的前10个单词。我的预期产出应该是:
W:A L:1
W:A's L:3
W:AA's L:4
W:AB's L:4
W:ABM's L:5
W:AC's L:4
W:ACTH's L:6
W:AI's L:3
W:AIDS's L:6
W:AM's L:4但这就是我得到的(注意L:s是怎么在另一条线上的,我想这就是问题所在):
W:A
L:2
W:A's
L:4
W:AA's
L:5
W:AB's
L:5
W:ABM's
L:6
W:AC's
L:5
W:ACTH's
L:7
W:AI's
L:5
W:AIDS's
L:7
W:AM's
L:5下面是我的代码:
FILE* dict = fopen("/usr/share/dict/words", "r"); //open the dictionary for read-only access
if(dict == NULL) {
return;
}
int i;
i = 0;
// Read each line of the file, and insert the word in hash table
char word[128];
while(i < 10 && fgets(word, sizeof(word), dict) != NULL) {
printf("W:%s L:%d\n", word, (int)strlen(word));
i++;
}发布于 2015-07-12 19:44:27
如果有足够的空间,fgets()会将换行符读入缓冲区。因此,您在打印word时会看到打印的换行符。从fget手册上看:
fgets()从流中读取最多小于一个小于大小的字符,并将它们存储到由s指向的缓冲区中。读取在EOF或换行符之后停止。如果读取换行符,则将其存储到缓冲区中。终止空字节('\0')存储在缓冲区中的最后一个字符之后。
(强调地雷)
你得自己修剪一下:
while(i < 10 && fgets(word, sizeof(word), dict) != NULL) {
size_t len = strlen(word);
if ( len > 0 && word[len-1] == '\n' ) word[len] = '\0';
printf("W:%s L:%d\n", word, (int)strlen(word));
i++;
}发布于 2015-07-12 19:45:04
原因是fget每次都会将换行符'\n‘拉到缓冲区word中,导致每次增加1次。
https://stackoverflow.com/questions/31371764
复制相似问题