首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C,getc/fgetc -终端空

C,getc/fgetc -终端空
EN

Stack Overflow用户
提问于 2016-01-18 16:40:25
回答 1查看 2.2K关注 0票数 0

我正在编写用C语言计算单词的程序,我知道我可以简单地用fscanf来完成这个任务。但我用的是getc。

我有这样的档案:

1 2 3 4 5。

我在when循环中读取字符,当我到达终端null时,断点就会出现。

c = fgetc(input);c = getc(input);会在One_之后和two_之后设置c = '\0';吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-18 17:08:09

当像getc()这样的函数的返回值为-1的EOF时,您已经到达file.try的末尾--这段代码用于计数单词:

代码语言:javascript
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34859776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档