如何在用 C++ 编写的控制台应用程序中制作加载动画? [英] How to make a loading animation in Console Application written in C++?
问题描述
我正在用 C++ 编写一个控制台应用程序,我需要使用 ASCII 字符来制作类似loading.gif"的东西.
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:
输出第 1 行: --输出第 2 行: \输出第 3 行: |输出第 4 行:/输出第 5 行: --
Output line 1: -- Output line 2: \ Output line 3: | Output line 4: / Output line 5: --
我需要这样做:
输出第 1 行: [这将一直被替换]
它不应该到第二行.
我怎样才能在 C++ 中做到这一点?有没有替换功能?
How can I do this in C++? Is there any kind of replace function?
推荐答案
您可以使用退格字符 ('\b'
) 返回并覆盖控制台上的字符.您还需要在每次更改后刷新输出,否则输出可能会保留在缓冲区中而不会出现在控制台上.
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.
这是一个简单的例子:
#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;
}
}
这篇关于如何在用 C++ 编写的控制台应用程序中制作加载动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!