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

C++ 如何制作一个只包含字符的简单加载屏幕?,c++,loading,C++,Loading,我正在尝试为我必须要做的模拟制作一个加载屏幕,这样控制台就不会在10秒钟内空白。我只想每隔2秒的模拟时间在一行中添加一个星号。这是我为加载屏幕提供的代码 #include <iostream> #include <cstdlib> #include <ctime> int main() { //initialize a random seed srand(time(NULL)); time_t simTime=10; time_

我正在尝试为我必须要做的模拟制作一个加载屏幕,这样控制台就不会在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);

#包括
#包括
#包括
int main()
{
//初始化随机种子
srand(时间(空));
时间=10;
时间经过时间=0;
时间\u t开始时间=时间(空);
做
{
时间\u t currentTime=时间(空);
passedTime=当前时间开始时间;
//模拟代码
如果(passedTime%2==0)

cout您实现了活动等待。您将需要两个线程:一个用于加载,另一个主要用于每隔两秒左右休眠并打印asterisc。可能类似于这样:

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();
}
bool加载完成;
无效打印加载()
{
做
{

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

#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;
}
#包括
#包括
使用名称空间std;
int main(){
浮动模拟持续时间=0.0;
浮动最大持续时间=10.0;
自开始或最后一次自动计时星号=时钟::高分辨率时钟::现在();
做{
//模拟代码
自动当前时钟=时钟::高分辨率时钟::现在();
std::chrono::duration time_since_last_asterisk=当前时间-time_since_start_或_last_asterisk;
if(自上次星号计数()以来的时间>=2.0){

cout目前你的代码将为2的每一个倍数打印这么多的星号。你应该以某种方式存储使用的乘法,避免打印重复的星号,或者使用不同的等待方法。我想我学校的编译器可能在c++98或其他什么上,因为我不能使用chrono headerWell,你介意接受其中一个答案吗两个答案都投票?线程答案也很好。