如何制作一个只包含字符的简单加载屏幕
How do I make a simple loading screen with just characters?
我正试图为我必须做的模拟制作一个加载屏幕,这样控制台就不会只有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;
}
相关文章:
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 无法将字符数组转换为包含 utf-8 字符的字符串
- 如何从 QString 中包含的十六进制值中获取 ASCII 字符?
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 如何制作一个只包含字符的简单加载屏幕
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何比较文件中包含的下一个字符
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何获取包含 NULL 字符的外壳代码字符串的长度
- 如果字符串向量包含字符'p',如何检查 c++
- C++ 检查 UTF8 字符串包含指定的字符
- 在 Windows 上,stat 和 GetFileAttributes 对于包含奇怪字符的路径失败
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 字符串只包含有效的字符?
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 当字符包含表情符号时如何比较字符?
- cout 打印的字符 [] 包含的字符数超过设置长度