c - scanf in a while loop reads on first iteration only -
note: please notice not duplicate of why scanf() causing infinite loop in code? , i've seen question issue there checks ==0
instead of !=eof
. also, problem different, "infinite loop" there still waits user input, not exit.
i have following while loop:
while ((read = scanf(" (%d,%d)\n", &src, &dst)) != eof) { if(read != 2 || src >= n || src < 0 || dst >= n || dst < 0) { printf("invalid input, should (n,n)"); } else matrix[src][dst] = 1; }
the intention of read input in format (int,int), stop reading when eof read, , try again if invalid input received.
the probelm is, scanf works first iteration, after there infinite loop. program not wait user input, keeps assuming last input same.
read
, src
, , dst
of type int
.
i have looked @ similar questions, seem fail checking if scanf returns 0 instead of checking eof
, , answers tells them switch eof
.
you need use
int c; while((c=getchar()) != '\n' && c != eof);
at end of while
loop in order clear/flush standard input stream(stdin
). why? answer can seen below:
the scanf
format string(" (%d,%d)\n"
) have requires user type
- an opening bracket(
(
) - a number(for first
%d
) - a comma(
,
) - a number(for last
%d
)
the space(first character of format string of scanf
) , newline character(\n
last character of format string of scanf
) considered whitespace characters. lets see c11 standard has whitespace characters in format string of fscanf
(yes. said fscanf
because equivalent scanf
when first argument stdin
):
7.21.6.2 fscanf function
[...]
- a directive composed of white-space character(s) executed reading input first non-white-space character (which remains unread), or until no more characters can read. directive never fails
so, whitespace characters skips/discards whitespace characters, if any, until first non-whitespace character seen in quote above. means space @ start of format string of scanf
cleans leading whitespace until first non-whitespace character , \n
character same.
when enter right data per format string in scanf
, execution of scanf
not end. because \n
hadn't found non-whitespace character in stdin
, stop scanning when finds one. so, have remove it.
the next problem lies when user types else not per format string of scanf
. when happens, scanf
fails , returns. rest of data caused scanf
fail prevails in stdin
. character seen scanf
when called next time. can make scanf
fail. causes infinite loop.
to fix it, have clean/clear/flush stdin
in each iteration of while
loop using method shown above.
Comments
Post a Comment