【发布时间】:2017-09-04 20:50:58
【问题描述】:
我需要读取一个带有数字的文件,然后将这些数字存储在一个数组中,之后我需要删除数组中出现的重复数字并订阅该文件。问题是我什至不能将文件上的数字放在整数数组中,我调试了代码并且文件确实打开了,但是同时无法将数字存储在数组中。
代码:
#include <stdio.h>
int main(void) {
int c;
int radica[50];
int i=0;
// open file
FILE *myFile = fopen("input.txt","r");//for ideone//fopen("input.txt", "r");
// if opening file fails, print error message and exit 1
if (myFile == NULL) {
perror("Error: Failed to open file.");
return 1;
}
rewind(myFile);
do{
fscanf(myFile,"%1d",&radica[i]); //Storing the number into the array
i++;
}while(feof(myFile));
// close file
fclose(myFile);
//printing the numbers
for(int j = 0; j < i; j++){
printf("%d\n", radica[j]);
}
return 0;
}
文件包含:1 2 3 4 5 6 7 5 8 8 6 3 4 5 6 6 7 7 8 8
【问题讨论】:
-
fsanf() 的返回值(不是 "radica" 中的读取值)是什么?根据 fscanf 文档说明它们是什么意思?
-
fscanf返回一个值,让您知道它是否有效,并且您的getc正在吃掉文件中的字符。 -
BTW
fclose是重复的。还有"EOF"-->EOF,j<50;-->j < i; -
如果看不懂你说的"still not working",我认为文件的格式和你想象的不一样。
-
while(feof(myFile));表示“到达文件末尾”...while(!feof(myFile));怎么样。但请记住,这意味着最后一次读取失败。
标签: c arrays file integer readfile