首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fgets函数C

fgets函数C
EN

Stack Overflow用户
提问于 2015-03-11 01:15:57
回答 1查看 131关注 0票数 1

首先,我想告诉大家,我还没有“深入研究”sgets()函数。下面是代码:

代码语言:javascript
复制
#include <iostream>
#include <stdio.h>

#pragma warning(disable:4996)

int main(){
    FILE* file;
    int count = 1;
    char buf[256];
    if (file = fopen("file.txt", "r"))
        while (!feof(file))
        {
            fgets(buf, 256, file);
            printf("%d string: %s", count, buf);
            ++count;
        }
    fclose(file);
    return 0;
}

这是我在file.txt中写的:

代码语言:javascript
复制
I
was
born
here
.

cmd中的输出为:

代码语言:javascript
复制
1 string: I
2 string: was
3 string: born
4 string: here
5 string: .
6 string: .

我怎么能拒绝5串的加倍呢?

EN

回答 1

Stack Overflow用户

发布于 2015-03-11 01:20:48

您可以进行以下更改,以查看代码是否按预期工作

代码语言:javascript
复制
    while (fgets(buf, 256, file) != NULL)
    {        
        printf("%d string: %s", count, buf);
        ++count;
    }

如前所述,不要像在代码中那样使用feof()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28970050

复制
相关文章

相似问题

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