充分利用用户的输入,而不必等待 - C语言..! [英] Getting an input from the user without having to wait - C language..!
问题描述
我目前编程一个简单的计时器,它从00年代到55岁以上运行,然后从00再次启动,并保持计数,直到用户停止它。为了这个目的我为用户两种选择:1.启动&安培; 2.复位。选择头号运行该程序,并选择排名第二,因为我认为它会关闭计时器,以00和保持它在那里。
I'm currently programming a simple timer, which runs from 00s to 55s and then start from 00 again and keeps counting until the user stops it. For that purpose I made two options for the user: 1. start & 2. reset. Choosing number one runs the program, and choosing number two, as I its supposed, will turn the timer in to 00s and keep it there.
现在我面临的问题是,我想从用户的输入而不停止定时器(即允许用户随时程序运行时,所以他可以停止正在进行的计数,而进入2)。我试图使用功能,如残培()和scanf(),但他们停止定时器,这完全破坏了程序。
Now the problem I'm facing is that I want to get an input from the user without stopping the timer (i.e. enabling the user to enter 2 at anytime while the program is running so he can stop the ongoing counting). I tried to use functions like getch() and scanf(), but they're stopping the timer, which is entirely ruining the program.
任何帮助AP preciated家伙.. !!
Any help appreciated guys..!!
推荐答案
您可以使用ncurses的做到这一点。在Windows上,类似的东西可以用的kbhit()来完成
和残培()
You can use ncurses to accomplish this. On Windows, something similar could be done with kbhit()
and getch()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <ncurses.h>
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;
}
这篇关于充分利用用户的输入,而不必等待 - C语言..!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!