0
我正在编写用C计算单词的程序,我知道我可以简单地用fscanf来做到这一点。但我正在使用getc。C,getc/fgetc - terminal null
我的文件是这样的:
一二三四五。
我读while循环和突破点是,当我到达终端空字符。
将c = fgetc(input);
或c = getc(input);
设置c = '\0';
之后one_和之后two_等?
我正在编写用C计算单词的程序,我知道我可以简单地用fscanf来做到这一点。但我正在使用getc。C,getc/fgetc - terminal null
我的文件是这样的:
一二三四五。
我读while循环和突破点是,当我到达终端空字符。
将c = fgetc(input);
或c = getc(input);
设置c = '\0';
之后one_和之后two_等?
当一个函数像getc()
返回值是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;
}
你为什么不试试呢?一次读取一个字符并打印其值。您可能还想阅读例如[this'fgetc'和'getc'参考](http://en.cppreference.com/w/c/io/fgetc)。 –
当然我尝试过。因为我访问数组越界,所以我在该循环中发生了段错误。我访问数组越界,因为c =='\ 0'不会发生。不过,我在问这个问题,因为我不确定这一点。 –
文件不是空终止的。 – EOF