【问题标题】:c++ get output one time in while loopc ++在while循环中获取一次输出
【发布时间】:2012-11-22 02:41:53
【问题描述】:

你好,我正在尝试在 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

它给我输出 Started 并且它只调用一次函数并继续刷新

【问题讨论】:

  • 设置一个 bool 标志以指示该函数已被调用 - 当时间不再匹配时清除它。
  • @sje397 为什么不回答这个问题?
  • 你能举个例子吗,我还是c++的初学者

标签: c++ time while-loop


【解决方案1】:

怎么样:

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);
}

你可以用函子做得更好,但这有点高级。

【讨论】:

  • 它仍然给我多个输出 :S 但没关系 :)
  • @beshoyMounir 是的,每次时间匹配时它都会调用一次 - 所以每天一次。对我来说似乎很有意义 :) 但如果你只想要一次,那么只需删除 else 子句即可。
【解决方案2】:

编辑:根据@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);
}
}

上面的代码将强制它只执行每个操作一次并继续刷新...

我的原评论:

在您发现的命令行/终端中,输出会连续打印出来。根据您使用的操作系统(window/linux/mac),解决方案将容易或不那么容易。

我建议查找gotoxy() 函数

http://www.programmingsimplified.com/c/conio.h/gotoxy

由 Windows 的“conio.h”库或 Linux 的“ncurses.h”库提供。

“ncurses.h”没有gotoxy(),但它会为您提供一种方法来做同样的事情。

【讨论】:

  • 问题不在于输出,而在于函数被多次调用(并打印了输出)而不应该被多次调用。
猜你喜欢
  • 2021-03-02
  • 1970-01-01
  • 2013-05-05
  • 2012-01-02
  • 2015-09-28
  • 2016-12-22
  • 2013-09-28
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多