zwhehe 发表于 2020-4-4 21:30:03

求助!!!文件读写后输出的数据完全不对

我试了一下文件读写操作发现输出的数据跟我输入文件的数据完全不一致啊

大概效果是我生成随机数3、2、5,结果程序输出0、151441、3546221

以下是代码,麻烦大佬们帮我看看是什么问题

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
        int i,num,ans;
        FILE *fp;
       
        for(i=0;i<30;i++)
        num=rand()%100;
       
        if((fp=fopen("input.ifo","wt+"))==NULL)
        {
                puts("文件打开失败!");
                exit(0);
        }
       
        for(i=0;i<30;i++)
        {
                fprintf(fp,"%d\n",num);
        }
       
        for(i=0;i<30;i++)
        {
                fscanf(fp,"%d\n",&ans);
        }
        for(i=0;i<30;i++)
        printf("%d   %d\n",num,ans);
        fclose(fp);
        return 0;
}

BngThea 发表于 2020-4-4 21:33:35

fscanf中不支持\n

zwhehe 发表于 2020-4-6 09:57:14

BngThea 发表于 2020-4-4 21:33
fscanf中不支持\n

谢谢!可是我去掉\n了还是不对怎么办啊

BngThea 发表于 2020-4-6 10:04:28

zwhehe 发表于 2020-4-6 09:57
谢谢!可是我去掉\n了还是不对怎么办啊

你写完后指针没有恢复到开头,在用完fprintf后加入一句
rewind(fp);

zwhehe 发表于 2020-4-6 14:24:57

BngThea 发表于 2020-4-6 10:04
你写完后指针没有恢复到开头,在用完fprintf后加入一句

麻烦蓝神了,可我加了rewind还是没有用{:10_266:}

大河之jian 发表于 2020-4-6 22:09:57

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main()
{
      int i,num,ans;
      FILE *fp;
      srand((unsigned int)(time(NULL)));
      for(i=0;i<30;i++)
                        num=rand()%100;
      
      if((fp=fopen("D:\\VC 6.0\\M.txt","wt+"))==NULL)
      {
                puts("文件打开失败!");
                exit(0);
      }
                rewind(fp);
      
      for(i=0;i<30;i++)
      {
                fprintf(fp,"%d\n",num);
      }
      rewind(fp);
      for(i=0;i<30;i++)
      {
                fscanf(fp,"%d\n",&ans);
      }
      for(i=0;i<30;i++)
                        printf("%d       %d\n",num,ans);
      fclose(fp);
      return 0;
}

zwhehe 发表于 2020-4-7 09:24:34

大河之jian 发表于 2020-4-6 22:09
#include
#include
#include


可以了,感谢老铁{:10_275:}

大河之jian 发表于 2020-4-7 11:48:20

zwhehe 发表于 2020-4-7 09:24
可以了,感谢老铁

不客气
页: [1]
查看完整版本: 求助!!!文件读写后输出的数据完全不对