C fscanf跳跃值

时间:2014-11-06 01:56:23

标签: c arrays file scanf

我正在尝试创建一个程序来读取文件中的值并将它们打印在屏幕上,现在部分打印出我的程序最终跳过某些值的文件。另一个问题,在这种情况下,如何动态为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]

2 个答案:

答案 0 :(得分:0)

更改为

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

答案 1 :(得分:0)

您正在迭代中执行两次文件读取,在以下位置更改条件:

while ((fscanf(fp," %f",&v[i])) != EOF);

为:

while(!feof(fp));

这可以防止价值跳过问题。希望这会有所帮助。