Limit time to Cin input

Asked

Viewed 162 times

1

I did a little research on, but I just find solutions spliced in C, but I use C++. The doubt is basically what the title says, whether it is possible to limit the time until the user input the cin.

cout << "Você tem 5 segundos para digitar algo";
cin >> input.

In this case, if the user enters something in up to 5 seconds, the input is recorded and the code goes to X place, otherwise something else happens and the code goes to Y place.

  • Create a child process, through Fork(), and fire a stopwatch that will end the program. If any input is entered in the parent process the process will terminate the stopwatch process (child).

  • Specifically for C++ study the thread class.

2 answers

1

Hello, all right?

You can use the clock() to determine the initial time, and as soon as the user enters something, you can also check with the clock() and determine the difference between the initial time and the final. If the difference is greater than 5 seconds, you direct the user to Y.

I guess if there’s a stop on the Cin, you will not be able to perform a scan while the user does not log in with the data.

I hope I helped you! Hugs.

  • clock cannot be used for this type of calculation, since it returns the time of the program in the processor (clock ticks).

0

In short, you would need an asynchronous reading of the input with std::cin, what is not possible.

What I believe is the best way is for you to lean on library C conium. h, specific for MS-DOS compatible platforms (that’s why I didn’t test the code I did, but I believe it works):

#include <stdio.h>
#include <conio.h>
#include <windows.h>

int main( void )
{
    printf("Pressione qualquer tecla para cancelar");
    for(int i = 20; i > 0; --i) {
        printf("\nO programa encerrara em %ds", i);
        if(kbhit()) {
            printf("\nTecla '%c' pressionada", getch());
            i = 21;
        }

        Sleep(1000);
    }
}

For options of functions kbhit and getch for Linux, see: Linux Conio (beta) or Using kbhit() and getch() on Linux.

Browser other questions tagged

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