I am trying to do a simple scanf
and printf
in the C program below:
- getting the user input
- checking if the user input is correct, if so, printing it out, else displaying a error message
Here is the code:
#include <stdio.h>
int main() {
int latitude;
int scanfout;
int started = 1;
puts("enter the value:");
while (started == 1) {
scanfout = scanf("%d", &latitude);
if (scanfout == 1) {
printf("%d\n", latitude);
printf("ok return code:%d\n", scanfout);
puts("\n");
} else {
puts("value not a valid one");
printf("not ok return code:%d\n", scanfout);
}
fflush(stdin);
}
return 0;
}
Tried compiling and running it at a command terminal, program works. command line output:
enter the value:
1
1
ok returncode:1
0
0
ok returncode:1
122.22
122
ok returncode:1
sad
value not a valid one
not ok returncode:0
As you can see, the program simply scans the user input and prints it out, it works fine in command line, but when it try to redirect the input to a text file say:
test < in.txt
the program doesn't work and the print statements in the else part goes on printing in an infinite loop. The text file in.txt
contains a single value 12
, instead of printing 12
, the program simply goes into a infinite loop and prints:
value not a valid one
not ok returncode:0
value not a valid one
not ok returncode:0
value not a valid one
not ok returncode:0
value not a valid one
not ok returncode:0
Can anyone help me with this? Is the code correct, why it works from command line and why file redirection doesn't work? help would be appreciated...