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:
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?
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;
}
}