简体   繁体   中英

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

So I want to make text appear that says "Loading" followed by 3 delayed dots, and have them start over again, like:

Loading.
Loading..
Loading...
Loading.

and so on, but always on the same line.

I looked into the delay function without the dos.h file (since I'm using gcc), but I'm not sure how to make the dots disappear and start again from the first one.

There's two things you need.

\\r , or carriage return, moves the cursor back to the beginning of the line.

Then normally stdout will not display anything until it sees a newline. This is called buffering and it needs to be turned off. You can do this with setvbuf() .

Here's a demonstration.

#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;
}

There are fancier ways to do this using the curses library , but \\r is enough for your purposes.

You need to use '\\r' character:

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", " ");
}

(Fixed: added fflush(stdout); )

The character '\\b' moves the cursor back one position. The following sequence gets what you want:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM