无需等待即可从用户那里获得输入 – C语言..!

我正在编写一个简单的计时器,它从00s到55s运行,然后再从00开始计数,并一直计数直到用户停止计时。 为此,我为用户提供了两个选项:1。启动和2.重置。 选择第一个运行程序,并选择第二个,因为我认为,将把计时器转为00s并保持在那里。

现在我面临的问题是我希望在不停止计时器的情况下从用户那里获得输入(即,在程序运行时允许用户随时输入2,这样他就可以停止正在进行的计数)。 我试图使用像getch()和scanf()这样的函数,但它们正在停止计时器,这完全破坏了程序。

任何帮助赞赏的人.. !!

您可以使用ncurses来完成此任务。 在Windows上,可以使用kbhit()getch()完成类似的操作

 #include  #include  #include  #include  #include  #include  #include  int main() { char ch = 0; int row = 0; int line = 0; int col = 0; int counting = 1; char text[80] = {""}; long int elapsed = 0; struct timeval start; struct timeval stop; initscr ( ); noecho ( ); timeout(100); getmaxyx ( stdscr, row, col); line = row / 2; snprintf ( text, sizeof ( text), "press 1 to exit or 2 to reset"); mvprintw ( line - 1, ( col - strlen ( text)) / 2,"%s", text); gettimeofday ( &start, NULL); while ( 1) { if ( counting) { gettimeofday ( &stop, NULL); elapsed = (stop.tv_sec - start.tv_sec); snprintf ( text, sizeof ( text), " %ld ", elapsed); mvprintw ( line, ( col - strlen ( text)) / 2,"%s", text); if ( elapsed > 54) { gettimeofday ( &start, NULL); } } else { snprintf ( text, sizeof ( text), "paused press 1 or 2"); mvprintw ( line, ( col - strlen ( text)) / 2,"%s", text); } //refresh ( ); if ( ( ch = getch ( )) == '1' || ch == '2') { if ( ch == '2') { counting = !counting; if ( counting) { gettimeofday ( &start, NULL); } } if ( ch == '1') { break; } } } endwin ( ); return 0; }