您可以使用 ncurses 来完成此操作。在 Windows 上,可以使用 kbhit() 和 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;
}