I have trouble with scanf and a loop on linux.
#include <stdio.h> #include <stdlib.h> #include <stdio_ext.h> int main(int argc, char ** argv){ int i = 0; char s[255]; char c; while(i<10){ printf("Here : "); scanf(" %s", s); printf("%sn", s); i++; while((c = getchar()) != 'n' && c != EOF); } return EXIT_SUCCESS; }
If in the shell Linux, if I execute my file like this :
echo "lol" | ./testWhileScanf
Then the result will be this :
Here : lol
Here : lol
Here : lol
Here : lol
Here : lol
Here : lol
Here : lol
Here : lol
Here : lol
Here : lol
I dont know why this is the result, a line of my code is to flush the stdin, to not have this kind of problem.
Seeking for solution I tried : __fpurge, fpurge, fflush But none worked.
I would like to get only :
Here ? : lol
Here ? :
And waiting for input. Surely I am missing something here.. but I can’t figure what =/
Advertisement
Answer
When you call
scanf(" %s", s);
for the first time, it sets s
to lol
, and returns 1
. When you call it for the second time, there is no further input, so scanf
returns zero without setting your variable. However, your code ignores the return value of scanf
, and prints s
anyway.
Adding a check and a break
should fix this problem:
if (scanf(" %254s", s) != 1) break;
Note the size limiter in the format string, it will prevent scanf
from causing buffer overruns.