【问题标题】:How to remove the garbage value read from the file? [closed]如何删除从文件中读取的垃圾值? [关闭]
【发布时间】:2017-09-21 14:35:15
【问题描述】:
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define N 50
struct Visitor
{
        char name[20];
        int y;
        char pass[20];
        int age;
        int oku;
        float price;
};

main()
{
        struct Visitor Data[N];

        FILE *fdata;
        int i = 1;

        fdata = fopen("data.txt", "r"); // read mode

        if (fdata == NULL)
        {
                perror("Error while opening the file.\n");
                exit(EXIT_FAILURE);
        }
        else
        {

                while (EOF != fscanf(fdata, "%s\t,%d\t,%s\t,%d\t,%d\t,%.2f\n", Data[i].name, &Data[i].y, Data[i].pass, &Data[i].age, &Data[i].oku, &Data[i].price))
                {

                        printf("%s\t,%d\t,%s\t,%d\t,%d\t,%.2f\n", Data[i].name, Data[i].y, Data[i].pass, Data[i].age, Data[i].oku, Data[i].price);
                        i++;
                }
        }
        fclose(fdata);
        return 0;
}

事实证明,我的文件的所有内容都显示在屏幕的左侧,然后在每一行都显示了一些垃圾值。我上面的编码有问题吗?我应该如何消除垃圾值?请帮忙..

附件是我的示例输出。 (左边那个是我的文件内容)

data.txt

【问题讨论】:

  • 你为什么只比较fscanf()s的返回值和EOF
  • 显示data.txt
  • 阅读sscanf 文档,了解它的返回值。仅针对 EOF 进行测试是不够的。您还必须检查sscanf 是否成功解析了您要求它解析的所有项目。第一步,将返回值读取到变量中以简化操作。
  • @xing 说得有道理.. omg 我试了一整天后终于解决了我的问题,非常感谢,其他人也非常感谢
  • @chux 最好建议删除问题?

标签: c file garbage


【解决方案1】:
#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<string.h>
#include <stdlib.h>
# define N 50
 struct Visitor{
  char name[20];
  int y;
  char pass[20];
  int age;
  int oku;
  float price;
 };

 main(){
  struct Visitor Data[N];

   FILE *fdata;
 int i=1;


   fdata = fopen("data.txt","r"); // read mode

   if( fdata == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
   else{

  while (EOF!=fscanf(fdata,"%19s%d%19s%d%d%f", &Data[i].name, &Data[i].y, &Data[i].pass, &Data[i].age, &Data[i].oku, &Data[i].price )){

  printf("%s\t,%d\t,%s\t,%d\t,%d\t,RM%.2f\n", Data[i].name, Data[i].y, Data[i].pass, Data[i].age, Data[i].oku, Data[i].price);
i++;
  }



}

   fclose(fdata);
   return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 2012-04-23
    • 2021-08-30
    相关资源
    最近更新 更多