-1

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.

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.

Any help appreciated guys..!!

1 Answers1

0

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;
}
user3121023
  • 8,181
  • 5
  • 18
  • 16