【问题标题】:fgets function and file handling in CC中的fgets函数和文件处理
【发布时间】:2019-04-12 01:49:15
【问题描述】:

我正在尝试制作一个程序,它将用户输入的数据存储在一个由用户提供名称的文本文件中。当用户进入退出时程序将终止。 string.h 的 strcmp 函数用于字符串比较,fgets() 用于从标准输入读取数据。

这是我的代码。

#include<stdio.h>
#include<string.h>

void main()
{
    char file[60];          // will store file name
    printf("Enter file name: ");
    fgets(file, 59, stdin);

    FILE *fp = fopen(file, "a+");   // open file in append mode

    if(fp == NULL){
        printf("File not found !");
        return;
    }

    char data[100];
    printf("Enter some data to add to file(exit to terminate): ");
    fgets(data, 99, stdin);

    int flag = strcmp(data, "exit");

    while(flag != 0){
        fputs(data, fp);

        fgets(data, 59, stdin);
        flag = strcmp(data, "exit");
        printf("%d\n", flag);       // for checking whether string are correctly comapred or not
    }

    printf("Bye");

}

即使我进入退出程序也不会终止。我还尝试在用户输入的字符串末尾连接“\n”,但这也无济于事。虽然,gets() 函数工作正常,但我知道它不是首选使用,我转移到 fgets() 但它对我不起作用。

【问题讨论】:

  • 您传递给fgets 的大小是带有 空终止符的。并始终检查它返回的内容。
  • I have also tried concatenating "\n" at the end of string input by user ..也许你需要剥离它。 :)
  • @SouravGhosh 还是将其添加到常量字符串文字中?
  • @Someprogrammerdude 很有可能...但不是很优雅...
  • 注意:char file[60]; fgets(file, 59, stdin)不需要负1,最好使用fgets(file, sizeof file, stdin)

标签: c


【解决方案1】:

检查man page 中的fgets(),它在输入后读取并存储换行符(由按ENTER 引起)。因此,strcmp() 失败。

您必须手动从换行符中删除输入缓冲区,然后才能比较输入。一种简单而优雅的方法是

 data[strcspn(data, "\n")] = 0;

【讨论】:

  • 你建议我怎么做?
  • @LakshyaMunjal 刚刚将其添加到我的答案中。
【解决方案2】:

fgets 读入一个完整的“行”,即一个字符序列,直到(包括!)一个新的行字符。因此,当用户按下“Enter”时,新行将成为读入字符串的一部分,strcmp(data,"exit") 将评估为“不等于”。

所以要么在比较之前去掉新行,要么与包含新行的字符串进行比较。由于您将数据按原样(即包括新行)写入文件,因此首先剥离新行然后手动将其添加到输出中似乎很麻烦。所以我实际上建议第二种方法:

fgets(data, 100, stdin);
flag = strcmp(data, "exit\n");

【讨论】:

    【解决方案3】:

    如果多余的字符无关紧要,另一种方法是使用strstr(即,如果用户键入“exit”或“asdfexitasdf”,您的程序将退出。-两者都包含“exit”。)

    所以

    int flag = strstr(data, "exit");
    if(flag != NULL)
        //exit the program
    else
        //stay in the program
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多