简体   繁体   English

C fscanf跳转值

[英]C fscanf jump values

I'm trying to make a program to read the values ​​in a file and prints them on the screen, now in part to print the files that my program ends up skipping some values​​. 我正在尝试制作一个程序来读取文件中的值并将其打印在屏幕上,现在部分是为了打印文件,我的程序最终跳过了一些值。 Another question, how would I do to allocate memory dynamically for v in this case? 另一个问题,在这种情况下如何为v动态分配内存?

file: 文件:

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

code: 码:

#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;
}

result: 结果:

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]

change to 改成

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

You are doing two file reads in an iteration, change the condition in while from: 您正在迭代中进行两次文件读取,请在以下时间内更改条件:

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

to: 至:

while(!feof(fp));

This should prevent the value skipping problem. 这样可以避免值跳过问题。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM