C++ 在 while 循环中获取一次输出

c++ get output one time in while loop

本文关键字:一次 输出 获取 while 循环 C++      更新时间:2023-10-16

你好,我正在尝试在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()但它会为你提供一种方法来做同样的事情。