[英]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. 我正在从我的字典中读取并打印出单词+单词的长度以用于测试目的。
I use strlen to get the length of the string. 我使用strlen来获取字符串的长度。 However, the numbers I got are not correct. 但是,我得到的数字不正确。 I believe strlen doesn't count the \\0 character. 我相信strlen不计算\\ 0字符。
I am reading the first 10 words in the dictionary. 我正在读字典中的前10个单词。 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
But this is what I got (Notice how the L:'s are on another line. I think this is where the problem is): 但这就是我得到的(请注意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
Below is my code: 以下是我的代码:
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()
reads in the newline into the buffer if there's enough space. 如果有足够的空间, fgets()
换行符读入缓冲区。 As a result, you see the newline printed when you print word
. 因此,您会在打印word
时看到打印的换行符。 From the fgets manual: 从fgets手册:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. fgets()从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。 Reading stops after an EOF or a newline. 读数在EOF或换行符后停止。 If a newline is read, it is stored into the buffer. 如果读取换行符,则将其存储到缓冲区中。 A terminating null byte ('\\0') is stored after the last character in the buffer. 终止空字节('\\ 0')存储在缓冲区中的最后一个字符之后。
(emphasis mine) (强调我的)
You have to trim it yourself: 你必须自己修剪它:
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++;
}
原因是因为fgets每次都会将换行符'\\ n'拉入缓冲区word
每次导致计数值增加1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.