下面的程序是一个简单的数字时钟,我想让时间与系统时间持续同步,并将其显示在控制台的顶部,而不让它干扰我的其他工作,因为在这种情况下,你可以看到第四行的"hello“永远不会打印出来,因为它上面的while循环永远不会结束,而且屏幕在每个循环中都会被清除。
我也希望我的代码在while循环之外执行指令,但它永远不会到达那个点,因为while循环在这个程序中永远不会结束
#include <ctime>
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
bool loop = true;
while (loop)
{
time_t now = time ( 0 );
tm *local = localtime ( &now );
local->tm_hour -= 6;
system("cls");
cout << ctime ( &now ) <<'\n';
cout<<"check";
Sleep(1000);
}
cout<<"hello";//this is not printed as while loop doesnt ends
cin.get();
return 0;
}发布于 2015-07-15 04:05:25
循环没有结束的原因是你没有结束它。您在开始时将loop设置为true,只要它保持为true,就会进行循环。但是,您实际上从未将其设置为false。
如果您的目标是创建一个在命令行顶部运行的时钟,这将有些困难,但并非不可能。
实际上,您需要做的就是使用ncurses这样的格式库不断地将光标放在要打印时间的行上,使用clrtoeol清除该行,打印时间,然后将光标放回最后一行。您还必须在主循环中放置一些内容,以获取用户的输入并将其发送到shell解释器,如下所示:
std::string command;
cin >> command;
system(command.c_str());不过,总的来说,使用unix date命令可能更容易,如下所示:
date "%H:%M:%S"每次你都需要知道现在几点了。
https://stackoverflow.com/questions/31412871
复制相似问题