我在数文件的字数。我写了下面的代码:
while ((ch = fgetc(fptr)) != EOF){ if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\0') { no_of_words = no_of_words + 1; }}
while ((ch = fgetc(fptr)) != EOF)
{
if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\0')
no_of_words = no_of_words + 1;
}
字符串对于一个包含以下内容的文本文件,它会将字数打印为8,而我期望的是6。
8
6
Hi, we are here.huio klhi
Hi, we are here.
huio klhi
型
t30tvxxf1#
因为当ch是一个换行符(\n)时,no_of_words也是向上计数的,所以文本文件中的两个额外的换行符也被算作新词。你可以做的是用另一个变量来跟踪你当前是否在一个单词中。每开始一个单词,就把它数一遍;但是当你在空白区域时不要计数:
ch
\n
no_of_words
#include <stdbool.h>#include <stdio.h>int main(void) { int ch; bool in_word = false; int no_of_words = 0; FILE *fptr = fopen("example.txt", "r"); while ((ch = fgetc(fptr)) != EOF) { if (ch == ' ' || ch == '\n' || ch == '\t') { in_word = false; } else if (!in_word) { in_word = true; no_of_words = no_of_words + 1; } } fclose(fptr); printf("words: %d\n", no_of_words); return 0;}
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int ch;
bool in_word = false;
int no_of_words = 0;
FILE *fptr = fopen("example.txt", "r");
if (ch == ' ' || ch == '\n' || ch == '\t')
in_word = false;
} else
if (!in_word)
in_word = true;
fclose(fptr);
printf("words: %d\n", no_of_words);
return 0;
字符串此外,不需要检查ch是否为\0(0),因为从fgetc接收的最后一个值将是EOF(通常定义为-1)。由于ch可以接收超过256个不同的值,因此必须使用int类型进行定义。
\0
fgetc
EOF
int
1条答案
按热度按时间t30tvxxf1#
因为当
ch
是一个换行符(\n
)时,no_of_words
也是向上计数的,所以文本文件中的两个额外的换行符也被算作新词。你可以做的是用另一个变量来跟踪你当前是否在一个单词中。每开始一个单词,就把它数一遍;但是当你在空白区域时不要计数:
字符串
此外,不需要检查
ch
是否为\0
(0),因为从fgetc
接收的最后一个值将是EOF
(通常定义为-1)。由于ch
可以接收超过256个不同的值,因此必须使用int
类型进行定义。