i want to read the first character of the string i enter:Code:int i; while(1) { fflush(stdin); i=fgetc(stdin); printf("%d\n",i); }
for example if I enter "1\n" it reads both the chars (2 cycles of the while) why doesn't the fflush resolve this?
This is a discussion on fflush and fgetc question within the Linux Programming forums, part of the Platform Specific Boards category; Code: int i; while(1) { fflush(stdin); i=fgetc(stdin); printf("%d\n",i); } i want to read the first character of the string i ...
i want to read the first character of the string i enter:Code:int i; while(1) { fflush(stdin); i=fgetc(stdin); printf("%d\n",i); }
for example if I enter "1\n" it reads both the chars (2 cycles of the while) why doesn't the fflush resolve this?
> why doesn't the fflush resolve this?
Because it's undefined?
Because you haven't read the FAQ?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
ok... i understand now that. but how can I fix it without fflush(stdin) ?
What do you want to fix?
Perhaps
if ( i != '\n' ) printf("%d\n",i);
Or read a line using fgets(), then parse that line to decide whether you're interested in each character (or not).
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.