【发布时间】:2015-10-18 22:00:23
【问题描述】:
**我对 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 稍后用于计算平均值,我最初是要求用户输入一个文件名,该文件名将整数写入文件)
【问题讨论】: