Variable reading in C with timeout

Asked

Viewed 543 times

1

Does anyone know how to limit the time the user can enter a value?

Example:

My program prints a value on the screen and the user has 4 seconds to type and enter, if what he typed is = to the printed value, the value changes and counts a point, otherwise the value changes and counts -1 point.

  • The solution will be different for different operating systems. It says if you use Windows, Linux, Android, spaceship, elevator controller, ..., ... (and le about ncurses) which eventually gives to your OS

1 answer

1

Updating

I noticed what the pmg said and went to research better on the subject, found some interesting things such as this code that works on linux, in addition the author referred to a library called Ncurses, and has also been referred to by pmg.

I also found an issue in the OS where they used the function select, however I thought about using threads so I searched again and I found a code that solves the problem.

#include <stdio.h>
#include <windows.h> 
 
#define TIMEOUT 4000 //4 segundos em milisegundos
 
void getInput(LPVOID param);
 
 
int main() {
 
    DWORD myThreadID;
    HANDLE myThread;
    int userInput = 0;
 
    myThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)getInput, &userInput ,0, &myThreadID);
 
    WaitForMultipleObjects(1, &myThread, TRUE, TIMEOUT);
     
    CloseHandle(myThread);
 
    if(userInput != 0){
        printf("\nValor %d", userInput);
    }else
       printf("\nO tempo limite foi excedido.");
 
    return 0;
}
void getInput(LPVOID param){
    printf("Insira o valor: ");
    scanf("%d",(int)&param);
}

Anyway I will keep the old solutions I had presented.


Using Unix Timestamp

We can measure the time difference using Unix Timestamp, the idea is very simple, we measure the start and then measure the end.

Example:

#include <stdio.h>
#include <time.h>
 
int main(void) {
    
    int valor; //variavel que guarda o "valor"
    printf("Insira um valor: "); 
    
    time_t _start = time(NULL); //medimos o tempo no instante inicial, ou seja, antes da execução do scanf.
    
    scanf("%d", &valor);
    
    time_t _end = time(NULL); //medimos o tempo no instante final, ou seja, depois da execuação do scanf.
        
    if((_end - _start) >= 4) //calculamos a diferença entre o final e o inicial, se o valor for superior a 4 então o tempo limite foi excedido.
    {
        printf("\nFoi excedido o tempo limite..");
    } else {
        printf("valor %d", valor);
    }
    return 0;
}    

Using the function clock

The code is the same what changes is the use of the clock function and the return, instead of returning a value in seconds this returns in milliseconds, hence it is necessary to multiply by 1000.

int main(void) {
    
    int valor; //variavel que guarda o "valor"
    printf("Insira um valor: "); 
    
    clock_t _start = clock(); //medimos o tempo no instante inicial, ou seja, antes da execução do scanf.
    
    scanf("%d", &valor);
    
    clock_t _end = clock(); //medimos o tempo no instante final, ou seja, depois da execuação do scanf.
    
        
    if((_end - _start) >= (4*1000) //calculamos a diferença entre o final e o inicial, se o valor for superior a 4000 então o tempo limite foi excedido.
    {
        printf("\nFoi excedido o tempo limite..");
    } else {
        printf("valor %d", valor);
    }
    return 0;
}

Using the QueryPerformanceCounter and QueryPerformanceFrequency

Thanks in advance to the deepmax for having published a time measurement code in the question: Measure Execution time in C (on Windows)

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
     
int main(void) {
    
    LARGE_INTEGER _frequency;
    LARGE_INTEGER _start;
    LARGE_INTEGER _end;
    double interval;
    
    int valor; //variavel que guarda o "valor"
    printf("Insira um valor: "); 
    
    QueryPerformanceFrequency(&_frequency);
    QueryPerformanceCounter(&_start); //medimos o tempo no instante inicial, ou seja, antes da execução do scanf.
    
    scanf("%d", &valor);
    
    QueryPerformanceCounter(&_end); //medimos o tempo no instante final, ou seja, depois da execuação do scanf.
    
    interval = (double) (_end.QuadPart - _start.QuadPart) / _frequency.QuadPart; //obtemos o intrevalo de tempo atravês da diferença entre o final e o inicial e a divisão da frequencia.

    
    if(interval >= 4.0) //verificamos se o intrevalo de tempo é superior a 4.0
    {
        printf("\nFoi excedido o tempo limite..");
    } else {
        printf("valor %d", valor);
    }
    return 0;
}

I hope that these examples give you a basic idea of how to measure time and how to do a time limitation.

  • The problem, I think, is not measuring how long it takes the user to input. The problem is to make that after 3 seconds it is considered white input (or something similar) ... that is: you cannot use fgets() (or scanf() or other "normal" method) directly because these functions block.

  • Well in the first logic that I had actually presented the time is measured, but it is from this measurement that I calculate the difference between the beginning and the end (_end - _start) and then determine if it was four seconds later. Anyway I researched more on the subject and found a solution using threads, in addition I also found a reference to Ncurses

Browser other questions tagged

You are not signed in. Login or sign up in order to post.