【发布时间】:2015-10-01 00:46:44
【问题描述】:
我正在阅读我的字典并打印出单词 + 单词的长度以进行测试。
我使用 strlen 来获取字符串的长度。但是,我得到的数字不正确。我相信 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: 是如何在另一行的。我认为这就是问题所在):
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++;
}
【问题讨论】:
-
fgets()的结果通常包括'\n'。要修剪,请参阅stackoverflow.com/a/28462221/2410359 BTW,格式很好的问题,虽然肯定是重复的。 -
“我相信
strlen不算'\0'字符。” ——不,它没有,也不应该这样做。 (任何对strlen函数的引用,包括man strlen,如果您的系统有手册页,都会告诉您这一点。)