**我对C还是很陌生,这是一个初学者的问题。我正在尝试从我已经写入的文件中读取由空格分隔的整数行,但是该行不起作用。当我尝试将整数打印到屏幕上时,我得到-1。我不确定为什么会这样:

#include <stdio.h>

int main() {
//create an array of characters
char str1[10];
//ask the user to enter a file name
printf("Enter a file name\n");
//str1 holds the address of the file name user enters
scanf("%s", str1);

FILE *fp;

fp = fopen(str1, "w+");
//write integer values to created file, separated by a space
fprintf(fp, "%d", 2);
fprintf(fp,"%c", ' ');
fprintf(fp, "%d", 4);
fprintf(fp,"%c", ' ');
fprintf(fp, "%d", 5);
fprintf(fp, "%c", ' ');
fprintf(fp, "%d", 7);
fprintf(fp, "%c", ' ');
fprintf(fp,"%d", 9);

int number;
int counter, c=0;
//if nothing is in file, then print error statement
if (fp==NULL){
    printf("File cannot be read");
}
c = fscanf(fp, "%d", &number);

while (c !=EOF){
    counter++;
    c = fscanf(fp, "%d", &number);
    printf("%d",c);
}
fclose(fp);

}


如何正确将整数打印到屏幕上? (稍后将使用count来计算平均值,我最初是要求用户输入一个将整数写入文件的文件名)

最佳答案

您遇到许多问题:


写入文件后,位置在文件末尾。需要rewind从文件的开头重新开始,然后再读取它。
printf应该打印number而不是c
在循环中,应将printf放在fscanf之前。否则,第一个数字将被遗漏,而最后一个打印是针对已返回fscanfEOF(即,number对于最后一种情况无效)。

07-24 09:46
查看更多