簡體   English   中英

如何創建偽造的“正在加載...”序列?

[英]How do I create a fake “Loading…” sequence?

因此,我想使文本顯示為“正在加載”,后跟3個延遲點,然后讓它們重新開始,例如:

Loading.
Loading..
Loading...
Loading.

依此類推,但始終在同一行。

我查看了沒有dos.h文件的延遲功能(因為我使用的是gcc),但是我不確定如何使這些點消失並從第一個開始重新開始。

您需要兩件事。

\\r或回車,將光標移回該行的開頭。

然后,通常stdout在看到換行符之前不會顯示任何內容。 這稱為緩沖,需要將其關閉。 您可以使用setvbuf()完成此操作。

這是一個示范。

#include <stdio.h>
#include <unistd.h>

int
main()
{
    /* Turn off stdout buffering */
    setvbuf(stdout, NULL, _IONBF, 0);

    for(int i = 0; i < 3; i++) {
        /* Clear the current line by moving to the start,
           overwriting it with spaces, and going back to the start.
        */
        printf("\r                                             \r");

        printf("Loading");

        /* Print ... over 3 seconds */
        for(int i = 0; i < 3; i++) {
            sleep(1);
            printf(".");
        }

        sleep(1);
    }

    /* Finish it all up with a newline */
    printf("\n");

    return 0;
}

有多種使用curses庫執行此操作的方法,但是\\r足以滿足您的目的。

您需要使用'\\ r'字符:

while (1) {
    int i;
    for (i=1; i<=3; i++) {
        printf("Loading%s\r", i==1 ? "." : i==2 ? "..":"...");
        fflush(stdout);
        sleep(1); /* or whatever */
    }
    printf("%20s\r", " ");
}

(修復:添加了fflush(stdout);

字符“ \\ b”將光標移回一個位置。 以下序列可滿足您的需求:

printf("Loading.");
while (not done yet) {
   delay
   printf(".");
   delay
   printf(".");
   delay
   printf("\b\b   \b\b"); // erase the last two dots, and move the cursor back again
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM