stupid fflush() problem.

Started by
3 comments, last by Abominus 22 years ago
why does fflush behave differently on Linux than a Win32 console? eg. fgets( buffer, sizeof(buffer)/sizeof(char), stdin ); if ( !strchr( buffer, "\n" ) ) fflush( stdin ); on linux, fflush() doesn''t have the desired effect, and the input spills over to the next fgets() call. Why?
Advertisement
The ANSI standard doesn''t specify the behaviour of flushing an input stream as far as I know, so the behaviour is undefined. This should work:
fgets(buffer, sizeof(buffer), stdin);if(!strchr(buffer, ''\n'')) while(fgetc(stdin) != ''\n'');

BTW: sizeof(char) is always 1, since sizeof returns the size of the data type measured in chars, not bytes. You should also use ''\n'' instead of "\n". I fixed both of these in my example.

quote:Original post by Null and Void
The ANSI standard doesn''t specify the behaviour of flushing an input stream as far as I know, so the behaviour is undefined. This should work:
fgets(buffer, sizeof(buffer), stdin);if(!strchr(buffer, ''\n'')) while(fgetc(stdin) != ''\n''); 

BTW: sizeof(char) is always 1, since sizeof returns the size of the data type measured in chars, not bytes. You should also use ''\n'' instead of "\n". I fixed both of these in my example.



Thanks. But are you sure about the second bit? sizeof returns the size of the data type in bytes. And sizeof char is not always 1, especially on Unicode/MCBS capable compilers.

quote:Original post by Abominus
...sizeof char is not always 1, especially on Unicode/MCBS capable compilers.

The standard specifies (IIRC) that sizeof(char) = 1 <= sizeof(short int) <= sizeof(long int) <= sizeof(float) <= sizeof(double) <= sizeof(long double)

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]
[ Google! | Asking Smart Questions | Jargon File ]
Thanks to Kylotan for the idea!
quote:Original post by Abominus
sizeof returns the size of the data type in bytes.

quote:Page 81, C99 Draft
6.5.3.4 The sizeof operator
...
3 When applied to an operand that has type char, unsigned char, signed char, (or a qualified version thereof) the result is one. ...
...


This topic is closed to new replies.

Advertisement