【问题标题】:Can't read integers from File one by one correctly无法正确地从文件中一一读取整数
【发布时间】:2021-04-27 19:09:31
【问题描述】:

在我的例子中,我可以将 50 个 4digits 随机生成的数字打印到名为 rastgele.txt 的文件中,但是我需要从文件中一个一个地读取它们并将它们存储在名为 的数组中>dosyaOkuma[] 并将它们打印到屏幕上。但是当我尝试扫描并打印它们时,我得到了不相关的数字,所以我无法从文件中正确读取它们。我需要一些关于正确从文件中读取 int 数字的帮助。

这是我的文件格式:

2862 3232 2869 2993 1303 3799 2257 2296 2105 3502 1318 3348 1851 3741 1468 1605 1994 1005 2211 1646 3056 3319 2273 1436 2621 1882 3856 2869 2026 2789 2055 1205 1263 1051 3059 3275 2876 1703 3674 1539 2381 2513 2415 3613 1066 3796 2710 2578 1294 3255

这是我的代码:

#include <stdlib.h>
int main(){
   FILE *file;
   int sayilar[50];
   int dosyaOkuma[50];
   int i,x,y;
   srand ( time(NULL) );
   for (i = 0; i < 50; i++) {
       int num = (rand() % 2999) +1000;
       sayilar[i] = num;
   }
   file = fopen("rastgele.txt","w");
   for(x=0;x<50;x++){
   fprintf(file,"%d  ",sayilar[x]);
   }
   printf("Olusuturulan rastgele sayilar rastgele.txt dosyasina yazdirildi...");

   for(y=0;y<50;y++){
   fscanf(file,"%d",&dosyaOkuma[y]);               //where ı read file...
   printf("\n%d. sayi = %1d",y+1,dosyaOkuma[y]);   //where ı print files to screen...
   }

   return 0;
}

这是我的程序输出:

1. sayi = 101
2. sayi = 0
3. sayi = -285212433
4. sayi = 32765
5. sayi = 0
6. sayi = 0
7. sayi = 0
8. sayi = 0
9. sayi = 0
10. sayi = 0
11. sayi = -1697181492
...

【问题讨论】:

  • 我改变了 w+ 而不是 w 但我得到相同的输出:(
  • 为了阅读,你需要回到文件的开头。 C I/O 函数只有一个“位置”,当您尝试读取它时,它位于您所写内容的末尾。
  • 另外注意,读取时不需要数组,只需一个int 变量。
  • 我明白了,我应该如何重构我的代码?
  • 对不起,我得到了相同的输出:(

标签: c file scanf


【解决方案1】:

包括stdio.htime.h
写后读前加rewind

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ( void){
    FILE *file = NULL;
    int sayilar[50] = { 0};
    int dosyaOkuma[50] = { 0};
    int i = 0, x = 0, y= 0;
    srand ( time(NULL) );
    for (i = 0; i < 50; i++) {
        int num = (rand() % 2999) +1000;
        sayilar[i] = num;
    }
    if ( NULL != ( file = fopen("rastgele.txt","w+"))) {
        for ( x = 0; x < 50; x++) {
            fprintf ( file,"%d  ",sayilar[x]);
        }
        printf ( "Olusuturulan rastgele sayilar rastgele.txt dosyasina yazdirildi...");
        rewind ( file);
        for ( y = 0; y < 50; y++) {
            if ( 1 == fscanf(file,"%d",&dosyaOkuma[y])) {
                printf("\n%d. sayi = %1d",y+1,dosyaOkuma[y]);
            }
        }
        fclose ( file);
    }

    return 0;
}

【讨论】:

  • 是的,你救了我的命,我很高兴!!
猜你喜欢
  • 1970-01-01
  • 2022-11-02
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多