<分区>
我目前正在编写一个程序,该程序接收未知数量的 double ,每个 double 来自文本文件中的每行。它应该将这些元素读入一个数组,但它不起作用。我的打印循环有效,但它只打印零。在来这里之前,我已经尝试了很多东西并查阅了很多东西。这是我的代码。
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Open an file to read from
FILE *file;
file = fopen("data.txt","r");
if (file == NULL)
{
printf("File not found.");
return -1;
}
//Count the number of lines in the input file
int numLines = 0; //CHANGE TO 1 ???
int ch;
do
{
ch = fgetc(file);
if (ch == '\n')
numLines++;
} while (ch != EOF);
//Put all of the data read into an array;
double input[numLines];
int i = 0;
while ((fscanf(file, "%lf\n", &input[i])) == 1)
i++;
//Close the file
fclose(file);
//Test printing elements of array
for (i = 0; i < numLines; i++)
printf("%lf\n", input[i]);
return 0;
}