问题
How I can use getchar() in a loop? Now I have...
for (p=0; p<n_players; p++) {
...
fflush(stdin);
getchar();
}
But it doesn't work... if n_players is 3, it execute getchar 2 times only at the end...
for (p=0; p<n_players; p++) {
blank_start();
ascii_art_title();
printf("%s, tocca a te...\n",player_info[p].player_name);
srand(time(NULL));
random_speed = MIN_WHEEL_SPEED + rand()%MAX_WHEEL_SPEED;
move_wheel_pointer(random_speed, &pointer);
if (player_points(&wheel[pointer]) == 0){
player_info[p].points = wheel[pointer];
}
else {
player_info[p].points = 0;
}
printf("\nGuadagni %d punti...\n",player_info[p].points);
if (p<(n_players-1)) {
printf("\nOra tocca a te, giocatore %d\n",(p+2));
}
fflush(stdin);
getchar();
}
getchar jumps the first loop
回答1:
Firstly, the result of flushing an input stream is undefined. Secondly, "doesn't work" does not give us a lot to go on.
回答2:
fflush
's behavior is not defined on an input stream, so the code as presented is nonsensical.
That loop will indeed happen 3 times if n_players is 3.
回答3:
getchar()
is not a good option to process user input. Having said that, if you still want to use that function, you can try by not using fflush
and piling up two calls to getchar
:
Something like this:
for (p=0; p<n_players; p++) {
...
c = getchar(); // c will hold character read
getchar(); // will consume '\n'
}
The thing with getchar()
is that it returns next character available in the keyboard buffer. So, if you do a c = getchar()
and user does:
E'\n'
(meaning he/she presses character E followed by ENTER)
c
will hold value 'E' and the next call to getchar()
will consume the ENTER ('\n') pressed by user.
So, as you can see, it's pretty tricky and hard to control properly.
If it is for testing some code, OK. If it is for a real application, try using platform dependent libraries to do user input (Win32 on Windows, GTK on Linux, ncurser on Linux, etc)
回答4:
1] fflush's on input stream is undefined behavior.
2] Your loop is indeed executed 3 times. The second call to getchar() will consume the ENTER
key from the stream that was put there the first time input was taken. Hence you think its getting called two times only.
Inshort, put one more getchar() to consume the \n
. That will solve your problem.
来源:https://stackoverflow.com/questions/2014755/c-getchar-in-a-loop