C++ 在 while 循环中获取一次输出
c++ get output one time in while loop
你好,我正在尝试在while循环中获取一次输出
While(1){
if( current->tm_hour == 10 && current->tm_min == 0 ){
Start_Function();
std::cout << "Started" << std::endl;
}
if( current->tm_hour == 12 && current->tm_min == 0 ){
End_Function();
std::cout << "Ended" << std::endl;
}
Sleep(5000);
}
我每 5 秒使用睡眠刷新一次
所以我希望当前小时和分钟= 10和00
它给我输出已启动,它只调用该函数一次,然后连续刷新
怎么样:
bool start_called = false, end_called = false;
While(1){
if( current->tm_hour == 10 && current->tm_min == 0 && !start_called ){
Start_Function();
std::cout << "Started" << std::endl;
start_called = true;
} else
start_called = false;
if( current->tm_hour == 12 && current->tm_min == 0 && !end_called ){
End_Function();
std::cout << "Ended" << std::endl;
end_called = true;
} else
end_called = false;
Sleep(5000);
}
你可以用函子做得更好,但这更高级一些。
编辑:根据@Joachim Pileborg的评论
问题不在于输出,而是在不应该调用函数时多次调用函数(并打印输出)。
替代解决方案
int hasStarted = 0, hasEnded = 0;
While(1){
if( current->tm_hour == 10 && current->tm_min == 0 && !hasStarted ){
Start_Function();
std::cout << "Started" << std::endl;
hasStarted = 1;
}
if( current->tm_hour == 12 && current->tm_min == 0 && !hasEnded ){
End_Function();
std::cout << "Ended" << std::endl;
hasEnded = 1;
}
Sleep(5000);
}
}
上面的代码将强制它只执行每个操作一次并继续刷新......
我最初的评论:
在命令行/终端中,当您发现输出时,输出会连续打印出来。根据您使用的操作系统(窗口/Linux/Mac),解决方案将很容易或不那么容易。
我建议查找gotoxy()
函数
http://www.programmingsimplified.com/c/conio.h/gotoxy
由Windows的"conio.h"库或Linux的"ncurses.h"提供。
"ncurses.h"没有gotoxy()
但它会为你提供一种方法来做同样的事情。
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- GCC 预处理器输出和编译一次通过,v2
- 代码只输出一次 std::vector,而不是多次输出
- 如何仅使输出打印一次
- 输入迭代器可以重复读取,而输出迭代器只能写入一次
- 在将数组与字符数组进行比较后需要帮助输出一次结果
- C++:如何一次输出两个字母的字符串
- 随机打印程序,尽管 sleep() 功能,一次打印多个输出
- C++ 在 while 循环中获取一次输出
- 使用一个 QPainter 一次绘制多个输出:SVG 和 QImage
- 启动 QProcess 并一次读取一行输出
- c++将输出(数字)保存到一个数组中.一次两个数字
- 一次接受多个输入,然后一次给出输出
- 为什么popn()一次又一次调用返回相同的输出
- 将两个正则表达式结果连接到一个输出字段中,一次只能使用一个
- GLUT只运行一次显示回调,不输出到终端