gpt4 book ai didi

c - 如何从fscanf循环中存在?

转载 作者:行者123 更新时间:2023-11-30 21:42:52 24 4
gpt4 key购买 nike

当没有更多数据可供读取时,我希望从循环中存在。我曾尝试过 !feof(fp), EOF,但它无限循环。如果我更改为 fscanf(fp, str, &str) == 1,它无法读取任何内容。这是代码:

void readFile(){

FILE *fp;
int i=0, j=1;
int* arr;
char str[45];


fp = fopen("c:\\Defuzzification.txt","r"); // read mode

if (fp == NULL) {
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}



arr = (int*)calloc(SIZE, sizeof(int));

while( fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr) == 1 ){
fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr);
printf("Display The different between frame %d and %d :%d\n", i, j, *arr);
i++;
j++;
}

fclose(fp);
}

while(fscanf(fp, "帧 %d 和 %d 之间的差异:%d", &i, &j, arr) != EOF) =>> 无限循环

while( fscanf(fp, "帧 %d 和 %d :%d 之间的差异", &i, &j, arr) == 1 ) =>> 不读取内容

输入数据:

The different between frame 0 and 1 :80
The different between frame 1 and 2 :58.18
The different between frame 2 and 3 :77.59
The different between frame 3 and 4 :71.24
The different between frame 4 and 5 :68.46
The different between frame 5 and 6 :75.81
The different between frame 6 and 7 :41.35

最佳答案

在下面的语句中,如果所有输入操作都成功,fscanf将返回3。

while( fscanf(fp, "The different between frame %d and %d :%d",  &i, &j, arr)  == 1 ){

将其更改为:

while( fscanf(fp, "The different between frame %d and %d :%d",  &i, &j, arr)  == 3 ){

另一件事...你有数字8058.18等。这些是 float 而不是整数。您不应该使用浮点格式并将其读取到浮点变量吗?

float number;
while( fscanf(fp, "The different between frame %d and %d :%f", &i, &j, &number) == 3 ){

更新

您需要进行以下更改:

  1. fscaf 的格式字符串中,放置一个空格作为第一个字符。这将跳过零个或多个空格,包括换行符。

  2. 使用 float 读取最后的数据。否则,数字的小数部分会留在输入流中,并且后续读取操作将失败。

  3. 您需要将while语句的条件中fscanf的返回值与3进行比较。如果fscanf能够成功读取全部三段数据,将返回3

使用以下代码块读取数据对我有用:

float number;
while( fscanf(fp, " The different between frame %d and %d :%f", &i, &j, &number) == 3 ){
fscanf(fp, " The different between frame %d and %d :%f", &i, &j, &number);
printf("Display The different between frame %d and %d :%f\n", i, j, number);
i++;
j++;
}

关于c - 如何从fscanf循环中存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28892591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com