我正在自学C++,但我的代码中有一个计时器.正在尝试在前一条消息后3秒对其进行定制

I am teaching myself C++ and got stuck with a timer in my code. Attempting to cout a message 3 seconds after the previous one

本文关键字:消息 3秒 一条 计时器 C++ 我的 有一个 代码      更新时间:2024-05-09

我在尝试定制一条延迟3秒的消息时遇到了问题。我可能试图通过使用后藤来艰难地做到这一点。如果有人有任何建议,我们将不胜感激。谢谢

代码:

#include <iostream>
#include <string>
using namespace std;
int seconds = 0;
int timer = seconds + 1;
int clock = timer;

int main() {
string namevar;
cout << "Enter your name: " << flush;
cin >> namevar;
std::cout << "Welcome " << namevar << ". This program was created to teach the user how to code using C++" "n";
clockf1:do {
seconds = timer;
if (clock < 3);
timer = seconds + 1;
goto clockf1;
}
while (clock == 3);
cout << "When learning any coding language the first step is to understand how to print Hello World. So let us begin!" << flush;
}

实际上,您可以用这种方式编写以等待3秒:

#include <bits/stdc++.h>
using namespace std;
using namespace this_thread; 
using namespace chrono;
int sec = 0;
int main(){
string namevar;
cout << "Enter your name: " << flush;
cin >> namevar;
cout << "Welcome " << namevar << ". This program was created to teach the user how to code using C++" "n";
do{
sleep_for(1s);//sleep for 1 sec
sec++;
cout << sec <<endl;
}while (sec<3);

cout << "When learning any coding language the first step is to understand how to print Hello World. So let us begin!" << flush;
return 0;
}

您可以在前面的文章中阅读更多关于this_threadchrono的内容。我也在复习c++,我可以向你推荐这本书。

我简化了上面的代码,去掉了do和while循环。我想如果有人感兴趣的话,我还不如把它发布在这里。再次感谢所有评论或发布代码以提供帮助的人!
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
using namespace std;
using namespace this_thread;
using namespace chrono;
const string term = "Hello World!";
int main() {
string namevar;
cout << "Enter your name: " << flush;
cin >> namevar;
std::cout << "Welcome " << namevar << ". This program was created to teach the user how to code using C++" "n";
sleep_for(2s);
cout << "When learning any coding language the first step is to understand how to print Hello World. So let us begin!" << endl;
}