开发者

Doesn't ANSI C allow printing each character at a same place after a fixed time period?

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 = 开发者_如何学Go0; i < 10; i++) {
    printf("%d", i);
    sleep(1);
    printf("\b");
}


stdout is probably buffered, so flush it.

for(i=0;i<10;i++)
 {
   printf("%d",i);
   fflush(stdout);
   sleep(1);
   printf("\b");
 }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜