C - how to handle user input in a while loop -
i'm new c , have simple programme takes user input within while loop, , quits if user presses 'q':
while(1) { printf("please come in choice: \n1)quit\n2)something"); *choice = getc(stdin); // actions. if (*choice == 'q') break; if (*choice == '2') printf("hi\n"); }
when run , nail 'q', programme quit correctly. if press '2' programme first prints out "hi" (as should) goes on print prompt "please take option" twice. if come in n characters , press enter, prompt gets printed n times.
this same behaviour happens when utilize fgets() limit of 2.
how loop working properly? should take first character of input , 1 time according entered.
edit
so using fgets() larger buffer works, , stops repeated prompt issue:
fgets(choice, 80, stdin);
this kind of helped: how clear input buffer in c?
when getc
input, it's of import note user has set in more 1 character: @ least, stdin
contains 2 chars:
2\n
when getc
gets "2" user has set in, trailing \n
character still in buffer, you'll have clear it. simplest way here add together this:
if (*choice == '2') puts("hi"); while (*choice != '\n' && *choice != eof)//eof in case *choice = getc(stdin);
that should prepare it
for completeness: note getc
returns int, not char
. create sure compile -wall -pedantic
flags, , check homecoming type of functions use.
it tempting clear input buffer using fflush(stdin);
, , on systems, work. however: this behavior undefined: standard states fflush
meant used on update/output buffers, not input buffers:
c11 7.21.5.2 fflush function, fflush works output/update stream, not input stream
however, implementations (for illustration microsoft) back upwards fflush(stdin);
extension. relying on it, though, goes against philosophy behind c. c meant portable, , sticking standard, assured code portable. relying on specific extension takes away advantage.
c
No comments:
Post a Comment