【问题标题】:How to read a file then store to array and then print?如何读取文件然后存储到数组然后打印?
【发布时间】:2015-06-09 09:02:48
【问题描述】:

程序的第一部分将整数写入一个名为“newfile.dat”的文件。 第二部分“想要”将整数存储到数组中。您能否解释一下我尝试将整数存储到数组中并打印的哪一部分是错误的?

#include <stdio.h>
#include <conio.h>
#define SIZE 3
int main(void){
    int murray[SIZE];
    int count;
    int n;
    int i;
    FILE*nfPtr;

    if((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","w"))==NULL)
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 1 begin

    printf("Enter numbers to be stored in file\n");//Here I am writing to the file. It works fine
    scanf("%d\n",&n);
    while (!feof(stdin)){
          fprintf(nfPtr,"%d\n",n);
          scanf("%d",&n);
          }
}//else 1 ends
        fclose(nfPtr);
    if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","r"))==NULL)//Here is where I try to read from file 
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 2 begin
        fscanf(nfPtr,"%d",&n);
        n=i;//Is this how I can add the file integers to program?
        while (!feof(nfPtr)){
              printf("%d\n",murray[i]);//Is this how I can get the array to print?
              }
        fclose(nfPtr);
}//else 2 ends
getch();
return 0;
}

【问题讨论】:

  • 关于读取数字的循环。 1) feof() 不能用作循环控制。建议将 scanf() 放在 while 语句中,检查 scanf() 的返回值。如果该返回值不等于 1,则退出循环/类似的问题适用于 fscanf() 调用以读取文件。

标签: c arrays printf scanf


【解决方案1】:

大约从底部算起的第 9 行。在n=i; 行中,您将未初始化变量i 的内容写入n,其中n 是您刚刚读取文件内容的变量。您希望muarray[i]=n; 填充数组。

话虽如此,您需要为i 赋值。所以你把它初始化为i=0;。每次填充数组时,都需要使用 i = i + 1;i++; 递增 i。

如果您没有错过这一点,您应该阅读有关循环和数组的主题。

【讨论】:

    【解决方案2】:

    这个贴出的代码:

        if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","r"))==NULL)//Here is where I try to read from file 
    {
        printf ("Sorry! The file cannot be opened\n");
    }
        else
    {//else 2 begin
            fscanf(nfPtr,"%d",&n);
            n=i;//Is this how I can add the file integers to program?
            while (!feof(nfPtr)){
                  printf("%d\n",murray[i]);//Is this how I can get the array to print?
                  }
            fclose(nfPtr);
    

    只调用一次 fscanf()。每次循环都需要调用 fscanf()。

    建议:

    if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","r"))==NULL)//Here is where I try to read from file 
    {
        perror("Sorry! newfile.dat cannot be opened for reading\n");
    }
    else
    {//else 2 begin
        while ( 1 == fscanf(nfPtr,"%d",&n))
        {
            printf("%d\n",n);  // cannot use uninitialized array: murry[]
        }
        fclose(nfPtr);
    } // end if
    

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2012-11-01
      • 2023-03-14
      • 2014-09-23
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多