I write console application which performs several scanf for int And after it ,I performs getchar :
int x,y;
char c;
printf("x:\n");
scanf("%d",&x);
printf("y:\n");
scanf("%d",&y);
c = getchar();
as a result of this I get c = '\n'
,despite the input is:
1
2
a
How this problem can be solved?
A way to clean up anyspace before your desired char and just ignore the remaining chars is
Call
fflush(stdin);
afterscanf
to discard any unnecessary chars (like \r \n) from input buffer that were left byscanf
.Edit: As guys in comments mentioned
fflush
solution could have portability issue, so here is my second proposal. Do not usescanf
at all and do this work using combination offgets
andsscanf
. This is much safer and simpler approach, because allow handling wrong input situations.You can use the fflush function to clear anything left in buffer as a consquence of previous comand line inputs:
For a start the
scanf
should readscanf("%d\n", &x);
or y. That should do the trick.man scanf
This is because
scanf
leaves the newline you type in the input stream. Tryinstead of