codeblocks - C - get character issue -
when run following code:
#include <stdio.h> #include <stdlib.h> int main() { int n; char y; printf("message\n"); fscanf(stdin, "%c", &y); printf("message\n"); fscanf(stdin, "%c", &y); return 0; }
i this:
message {enter character} message
the problem not asked enter character twice if there 2 scanf functions. output should this:
message {enter character} message {enter character}
i have issue getc()
too:
#include <stdio.h> #include <stdlib.h> int main() { int n; char y; printf("message\n"); y=getc(stdin); printf("message\n"); y=getc(stdin); return 0; }
also, fflush()
not help:
#include <stdio.h> #include <stdlib.h> int main() { int n; char y; printf("message\n"); y=getc(stdin); fflush(stdin); fflush(stdout); printf("message\n"); y=getc(stdin); return 0; }
i've tried fflush stdin, stdout, stdin+stdout (at same time), result still same.
change
fscanf(stdin, "%c", &y);
to
fscanf(stdin, " %c", &y);
quoting c11 standard:
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, space before %c
discards \n
character left on first fscanf
. did character come from? recall press enter key after enter character. character not consumed first fscanf
, stays in standard input buffer(stdin
).
this happens in second version of program,i.e, second getc
gets newline character left on first one. can use following code flush(clear) stdin
:
int c; while((c=getchar())!=eof && c!='\n');
as why fflush(stdin);
dosen't work standard says behavior undefined:
7.21.5.2 fflush function
[...]
- if stream points output stream or update stream in recent operation not input, fflush function causes unwritten data stream delivered host environment written file; otherwise, behavior undefined.
but note fflush(stdin)
does work in implementations. read this
Comments
Post a Comment