[Solved] How to exist from fscanf loop?


In the following statement, fscanf will return 3 if all the input operations are successful.

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

Change it to:

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

Another thing… You have numbers 80, 58.18, etc. These are floating point numbers not integral number. Shouldn’t you be using a floating point format and read it to a floating point variable?

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

Update

You need to make the following changes:

  1. In the format string to fscaf, put a space as the first character. This will skip zero or more white spaces, including newline characters.

  2. Use a floating point number to read the last data. Otherwise, the fractional part of the number gets left behind in the input stream and the subsequent read operation fails.

  3. You need to compare the return value of fscanf in the conditional of the while statement to 3. fscanf will return 3 if it is able to successfully read all the three pieces of data.

Using the following block of code for reading the data works for me:

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

7

solved How to exist from fscanf loop?