c++ - 如何告诉我的程序在等待用户命令时做某事?

标签 c++

我正在尝试制作一个计时器,该计时器将从用户发出命令的时间开始计数,直至为零。

现在我正在尝试向它添加一个暂停派系,这将要求我的程序在计时器滴答时接受和读取输入。

这是我目前的代码 -

#include <iostream>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
using namespace std;
//  sleep(5000);

int seconds;
int hoursLeft;
int minutesLeft;
int secondsCount=0;
void timeLeft ()
{
    hoursLeft = seconds/3600;
    minutesLeft = seconds/60 - hoursLeft*60;
}
void timer ()
{
    if (secondsCount == 60)
    {
    timeLeft();
    cout << "The Amount of time left is: " << hoursLeft << " hours and " << minutesLeft << " minutes left." << endl;
    secondsCount=0;
    }
    secondsCount++;
    seconds--;
    Sleep(1000);
    timer();
}
int main()
{
    // introduction and time picking
    cout << "Welcome to my Timer - Please set the amount of hours and than minutes you want the timer to run" << endl;
    double requestedHours, requestedMinutes;
    cin >> requestedHours;
    cin >> requestedMinutes;
    double requestedSeconds = requestedHours*3600 + requestedMinutes*60;
    seconds = requestedSeconds;
    cout << "Timer Started";
    timer();
}

最佳答案

#include <stdio.h>
#include <fcntl.h>
#include <string.h>

int main()
{
    char    buffer[16];
    int     flags;
    int     fd;
    int     r;

    fd = 0; //stdin
    flags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    while (1)
    {
        memset(buffer, 0, sizeof(buffer));
        r = read(0, buffer, sizeof(buffer)); //return the number of bytes it reads
        if (r > 0)  //something was read
        {
            printf("read: %d\n", buffer[0]);
            fflush(stdin);
        }
        else    //nothing has been read
        {
            puts("update timer here");
        }
        usleep(50000);
    }
    return (0);
}

在文件描述符上使用非阻塞读取也很酷

抱歉,我只有 C 语言的解决方案

PS:你的计算机不应该无限递归地工作,你应该使用循环而不是无限递归(timer() 自行召回),否则你的堆栈将溢出

关于c++ - 如何告诉我的程序在等待用户命令时做某事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30836552/

相关文章:

c++ - 在 C++ 运行时从指针访问对象实例

C++调用静态成员函数指针

c++ - 循环不正常

c++ - mmap 和 C++ 严格的别名规则

c++ - omn​​et : Simulation terminated with exit code: 139 中的导航层次结构错误

javascript - Node.js fs.open() 在尝试打开超过 4 个命名管道 (FIFO) 后挂起

c++ - 使用可变参数模板和重载 << 运算符编译错误

c++ - 我怎样才能知道是否可以使用它使数组中的数字相等?

c++ - 理解 C++ 中的指针

c++ - 在同一行中声明成员引用变量