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

梦想与她 提交于 2019-12-11 00:30:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!