j.yang29
j.yang29

Reputation: 65

Why does printf not print anything after my while loop

Here's my code

#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int x = 0;
    int y = 0;
    float a[5][2];      //array
    float b[3][2];      //array
    float c[2][2];      //array
    FILE *fr;
    //int c;
    float power;
    char unit[5];
    //int N;        //Number of sensors
    float TI;       //Time interval
    //char M;       //Midpoint
    //char T;       //Trapezoid
    //int SR;       //Sample Rate
    fr = fopen("sensor_0.txt","r");
    /*fr = fopen("sensor_1.txt","r");
    fr = fopen("sensor_2.txt","r");
*/
//----------------------------------------------------------------------------------------------------------------------------
 printf("The contents of %s file are :\n", "sensor_0.txt");
 while ( !feof( fr ) )
 {


fscanf(fr, "%f %f %s",&TI, &power, unit);

//printf("%f, %f \n", TI,power);        //print
a[x][y] = TI;
a[x][++y]= power;
x++;
y = 0;

 }
  fclose(fr);
//----------------------------------------------------------------------------------------------------------------------------

  printf("%s", "hello");

    return 0;
}

Why isn't my string printing out anything after the while loop? If I uncomment the same line inside the while loop, it prints properly. I've also tried just adding simple printf("hello") yet nothing seems to work after the while loop.

Edit - minor formatting.

output should just be
700 25.18752608 mW
710 26.83002734 mW
720 26.85955414 mW
730 23.63045233 mW

Upvotes: 0

Views: 1107

Answers (2)

chqrlie
chqrlie

Reputation: 144770

I suspect the file has 5 lines, not 4.

Your test of !feof() fails because you have not hit the end of file yet when you try to read the 6th line. fscanf fails but you do not test the return value. So you store TI and power beyond the end of the 2D array, invoking undefined behavior.

Changing the loading code this way should fix the problem:

while (x < 5 && fscanf(fr, "%f %f %4s", &TI, &power, unit) == 3) {
    a[x][0] = TI;
    a[x][1] = power;
    x++;
}
if (x != 5) {
    printf("incomplete input\n");
}

Upvotes: 2

j.yang29
j.yang29

Reputation: 65

Doing what chqrlie suggested worked.
"instead of while ( !feof( fr ) ) that is incorrect, use while (fscanf(fr, "%f %f %4s",&TI, &power, unit) == 3)"

Upvotes: 0

Related Questions