strlen没有给出正确的字符串长度C. [英] strlen not giving correct string length C
问题描述
我正在从我的字典中读取并打印出单词+单词的长度以用于测试目的。
I am reading from my dictionary and printing out the word + the length of the word for testing purposes.
我使用strlen来获取字符串的长度。但是,我得到的数字不正确。我相信strlen不计算\0字符。
I use strlen to get the length of the string. However, the numbers I got are not correct. I believe strlen doesn't count the \0 character.
我正在读字典中的前10个单词。我的预期输出应为:
I am reading the first 10 words in the dictionary. My expected output should be:
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:如何在另一条线上。我认为这就是问题所在):
But this is what I got (Notice how the L:'s are on another line. I think this is where the problem is):
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()
将换行符读入缓冲区有足够的空间。因此,当您打印 word
时,会看到打印的换行符。来自fgets手册:
fgets()
reads in the newline into the buffer if there's enough space. As a result, you see the newline printed when you print word
. From the fgets manual:
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++;
}
这篇关于strlen没有给出正确的字符串长度C.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!