【发布时间】: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() 调用以读取文件。