C、getc/fgetc——终端为空

C, getc/fgetc - terminal null

我正在用 C 编写计算单词的程序,我知道我可以用 fscanf 简单地做到这一点。但是我正在使用getc。

我有这样的文件:

One two three four five.

我正在 while 循环中读取字符,断点是当我到达终端 null 时。

c = fgetc(input);c = getc(input); 会在 One_ 之后和 two_ 之后设置 c = '[=13=]'; 等吗?

当像getc()这样的函数的return值为EOF即-1时,那么你已经到达file.try这段代码的末尾来计算单词:

#include <stdio.h>

int WordCount(FILE *file);

int main(void)
{
    FILE *file;
    if(fopen_s(&file,"file.txt","r")) {
        return 1;
    }
    int n = WordCount(file);
    printf("number of words is %d\n", n);
    fclose(file);
    return 0;
}

int WordCount(FILE *file)
{
    bool init = 0;
    int count = 0, c;
    while((c = getc(file)) != EOF)
    {
        if(c != ' ' && c != '\n' && c != '\t') {
            init = 1;
        }
        else {
            if(init) {
                count++;
                init = 0;
            }
        }
    }
    if(init)
        return (count + 1);
    else
        return count;
}