-1

This is the code

int
read_data(void){
    char type;
    double x_val,y_val,noise_val;   
    while (scanf("%c %lf %lf %lf",&type,&x_val,&y_val,&noise_val)==4){
        printf("%c %lf %lf %lf",type,x_val,y_val,noise_val);
    }
    return 0;
}

the input is

N 501.0 7501.0 80.0
N 1001.0 5001.0 90.0
N 3501.0 7501.0 130.0
N 5001.0 2001.0 85.0

when I enter after compiling as test < testing.txt it only prints the first line.

However if i remove the while loop and keep adding more scanfs and prints this is the output.

N 501.000000 7501.000000 80.000000

 501.000000 7501.000000 80.000000
N 1001.000000 5001.000000 90.000000

 1001.000000 5001.000000 90.000000
N 3501.000000 7501.000000 130.000000

 3501.000000 7501.000000 130.000000
N 5001.000000 2001.000000 85.000000

 5001.000000 2001.000000 85.000000

what is going wrong?

zkvsl
  • 87
  • 1
  • 7

1 Answers1

3

The problem is that the scanf call doesn't read the newline after the first line, it will still be in the input buffer, so the next time you call scanf the "%c" format will read that newline, and then attempt to read the character N as a floating point number, which will fail and the loop will exit.

A simple solution is to use fgets to read the lines, and then use sscanf to parse the lines you have read.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621