问题
I am trying to generate random numbers to be printed on the console. I am programming in C on Linux. I wanted to print all the numbers at a single place after a time interval of a second for each number.
I am using sleep()
for stopping a 'time interval'. I tried \b
, \r
and all but none works.
I just wanted this to run, for example:
for (i = 0; i < 10; i++) {
printf("%d", i);
sleep(1);
printf("\b");
}
回答1:
stdout is probably buffered, so flush it.
for(i=0;i<10;i++)
{
printf("%d",i);
fflush(stdout);
sleep(1);
printf("\b");
}
回答2:
The easiest answer is probably to use ncurses:
#include <ncurses.h>
int main()
{
int i;
initscr(); /* Start curses mode */
for (i=0;i<10;i++) {
mvprintw(0,0, "%d", i); /* coords 0,0 */
refresh(); /* Update screen */
sleep(1);
}
getch(); /* Wait for user input */
endwin(); /* End curses mode */
return 0;
}
Compile with gcc -o counter counter.c -lncurses
.
来源:https://stackoverflow.com/questions/5056247/doesnt-ansi-c-allow-printing-each-character-at-a-same-place-after-a-fixed-time