如何制作一个只包含字符的简单加载屏幕

How do I make a simple loading screen with just characters?

本文关键字:字符 包含 简单 屏幕 加载 一个 何制作      更新时间:2023-10-16

我正试图为我必须做的模拟制作一个加载屏幕,这样控制台就不会只有10秒的空白。我只想在每2秒的模拟时间里给一行添加一个星号。这是我为加载屏幕想出的代码。

#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
//initialize a random seed
srand(time(NULL));
time_t simTime=10;
time_t passedTime=0;
time_t beginTime=time(NULL);
do
{
time_t currentTime=time(NULL);
passedTime=currentTime-beginTime;
//Code for simulation
if(passedTime%2==0)
cout<<"*";
cout<<endl;
}while(passedTime<simTime);

它只是在10秒内不停地打印出星号。

您实现了主动等待。你需要两个线程:一个是加载线程,另一个是每隔两秒左右休眠并打印星号

bool loadingComplete;
void PrintLoading()
{
do
{
std::cout << '*';
std::this_thread::sleep_for(2s);
}
while(!loadingComplete);
}
void LoadStuff()
{
// Long running task
}
int main()
{
std::thread t(PrintLoading);
loadingComplete = false;
LoadStuff();
loadingComplete = true;
t.join();
}

如果不主动中断线程,这可能会比需要的时间长2秒,而且我没有时间进行测试,但我希望它能为您指明正确的方向。

如果您只是想在循环中进行类似操作时打印出星号,则不一定需要单独的线程。下面是一个基于您的代码的示例:

#include <chrono>
#include <iostream>
using namespace std;
int main() {
float simulation_duration = 0.0;
float maximum_duration = 10.0;
auto time_since_start_or_last_asterisk = chrono::high_resolution_clock::now();
do {
//Code for simulation
auto current_time = chrono::high_resolution_clock::now();
std::chrono::duration<double> time_since_last_asterisk = current_time - time_since_start_or_last_asterisk;
if (time_since_last_asterisk.count() >= 2.0){
cout << "*";
cout.flush();
simulation_duration += time_since_last_asterisk.count();
time_since_start_or_last_asterisk = current_time;
}
} while (simulation_duration < maximum_duration);
cout << endl;
}