我正在尝试制作一个程序来读取文件中的值并将其打印在屏幕上,现在部分是为了打印文件,我的程序最终会跳过一些值。另一个问题,在这种情况下如何为v动态分配内存?

文件:

3 -1 1 3 1
2 2 1 -3.4
5 -1 -2 5 0 -3 1


码:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define N 100

int main(){
float *v;
int i=0;

v=(float*)malloc(N*sizeof(float));

FILE* fp;
fp = fopen("entrada.txt","rt");
if (fp == NULL) {
printf("Erro na abertura do arquivo!\n");
exit(1); }

do{
fscanf(fp," %f",&v[i]);
printf("v[%d] = [%f]\n",i,v[i]);
i++;
}
while ((fscanf(fp," %f",&v[i])) != EOF);

int fclose (FILE* fp);
system("pause");
return 0;
}


结果:

v[0] = [3.00000]
v[1] = [1.00000]
v[2] = [1.00000]
v[3] = [2.00000]
v[4] = [-3.00000]
v[5] = [-1.00000]
v[6] = [5.00000]
v[7] = [-3.00000]
v[8] = [1.00000]

最佳答案

改成

while ((fscanf(fp," %f",&v[i])) != EOF){
    printf("v[%d] = [%f]\n",i,v[i]);
    i++;
}

10-06 09:17