我正在尝试将文件读入数组,但是代码无法运行。说我试图给一个指针赋值。
#include <stdio.h>
int main(void)
{
FILE *ifile;
float num;
float*numbers[8001];
float pointer = numbers;
int i = 0;
ifile = fopen("lotsOfNumbers.txt", "r");
if (ifile == NULL) {
printf("File not found!! Exiting.\n");
}
else {
while (fscanf(ifile, "%f ", &num) != EOF) {
//printf("I read %d from the file. \n", num);
numbers[i] = #
if (i < 8801) {
i++;
}
else return 0;
}
}
fclose(ifile);
}
答案 0 :(得分:2)
您的代码中有很多错误。您可能想要这样:
#include <stdio.h>
int main(void)
{
FILE *ifile;
float num;
float numbers[8001]; // you just need an array of float, no pointers needed
int i = 0;
ifile = fopen("lotsOfNumbers.txt", "r");
if (ifile == NULL) {
printf("File not found!! Exiting.\n");
}
else {
while (fscanf(ifile, "%f ", &num) != EOF) { // &num instead of num
printf("I read %f from the file.\n", num); // use %f for printing a float, not %d
numbers[i] = num;
if (i < 8001) { // 8001 instead of 8801
i++; // using a constant or a #define avoids this kind of errors
}
else
return 0;
}
fclose(ifile); // close file only if it has been opened sucessfully
}
// fclose(ifile); // that was the wrong place for fclose
}
注释中有解释。