J
James Kuyper
Yes, of course, but I don't understand *exactly* why it's required, as
in, I haven't seen for myself, but I'll get there.
Your call to printf() doesn't include a newline character before calling
fgets(). If stdout is unbuffered, it should work exactly as you expect,
but that's pretty uncommon. stdout is normally line-buffered, in which
case the user won't see any output until the next time your program
prints a newline.
stdout is permitted to be fully buffered only if the implementation
cannot determine that stdout is connected to an interactive device.
Systems where that can be determined are commonplace, and
implementations for systems where it cannot be determined will generally
not take advantage of that fact. However, if an implementation does
choose to fully buffer stdout, the failure mode is even more confusing:
if your call to printf() doesn't fill up the buffer, the user won't see
anything. If it does fill up the buffer, the buffer will be output, but
it's likely to be the case that only part of your prompt will be
printed, the rest will be put at the beginning of the newly-flushed buffer.
int getChoice2(void){
int BUFSIZE = 4;
char buffer[BUFSIZE];
int count = 0, choice = 0;
while(count == 0 || count == EOF){
printf("%s", "Input an integer >> ");
fflush(stdout);
if(NULL != fgets(buffer, BUFSIZE, stdin)){
count = sscanf(buffer, "%d", &choice);
stdin[0]._IO_read_ptr = stdin[0]._IO_read_end;
It is generally an extremely bad idea to fiddle with the contents of a
FILE*. In addition to making your code unportable, there's a pretty good
chance that your fiddling with that structure may interfere with use of
Well I can't comment on that as I only have a Linux box here. I think I
have an old Windows machine around somewhere, maybe I'll dig it out
although the processor architecture is likely the same.
It's the architecture of <stdio.h> that matters, the processor
Anyway, if you look at how
getchar();
fgetc();
scanf();
and
fgets();
work they all work by advancing the read pointer if they successfully
read one or or more characters, advancing the read pointer 'by hand'
simply simulates a read ... it's just much, much faster.
The fact that they work that way is highly system-specific. Don't expect
any portability, whatsoever, of code that is based upon such assumptions.