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

时间:2015-06-15 02:17:54

标签: 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();
}

1 个答案:

答案 0 :(得分:0)

#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()召回本身),否则你的堆栈会溢出