Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a loading animation in Console Application written in C++?

I am coding a Console Application in c++ and I need to make something like a "loading.gif" just by using ASCII characters.

The following is the list of the characters that I should be using:

  1. --
  2. \
  3. |
  4. /
  5. --

These symbols will make a loading animation by cycling.

However, when I write the output, it become like:

Output line 1: -- Output line 2: \ Output line 3: | Output line 4: / Output line 5: --

I need to do this like this:

Output line 1: [this will be replaced all the time]

It should never go to the second line.

How can I do this in C++? Is there any kind of replace function?

like image 277
Aristona Avatar asked Dec 13 '11 08:12

Aristona


People also ask

What is loader animation?

Loading animations are notifications that reassure users that the system is still handling their request. When a user clicks on a link or button, the animation is displayed until the load process is complete. Some animations have progress bars that indicate how long it will take for data or content to load.


1 Answers

You can use the backspace character ('\b') to go back and overwrite characters on the console. You'll also need to flush the output after each change, otherwise the output might stay in a buffer and not appear on the console.

Here is a simple example:

#include <iostream>
#include <unistd.h> // for sleep()

int main()
{
    std::cout << '-' << std::flush;
    for (;;) {
        sleep(1);
        std::cout << "\b\\" << std::flush;
        sleep(1);
        std::cout << "\b|" << std::flush;
        sleep(1);
        std::cout << "\b/" << std::flush;
        sleep(1);
        std::cout << "\b-" << std::flush;
    }
}
like image 199
Mike Seymour Avatar answered Sep 24 '22 05:09

Mike Seymour