A scanf that can timeout.

A fonction that gives you 20 secondes to type a number.

getch,kbhit,time.h

See version :

Pas de dépendances

Download :

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int timeoutgetnb(int* remaining,const char* chaine)
{
    int timeleft;
    char cache[11] = {0};
    int curs = 0;
    time_t starttime = time(NULL);
    printf("\r%s [%d] : %s          ",chaine,*remaining,cache);    
    do 
    {
        time_t crt = time(NULL);
        if (difftime(crt,starttime)>=1.0)
        {
            starttime = crt;
            (*remaining)--;
            printf("\r%s [%d] : %s          ",chaine,*remaining,cache);    
        }
        if (_kbhit())
        {
            char c = (char)getch();
            if (c>='0' && c<='9' && curs<10)
                cache[curs++] = c;
            if (c==0x0D)
            {
                printf("\n");
                return atoi(cache);
            }
            if (c=='\b' && curs!=0)
                cache[--curs] = '\0';
            printf("\r%s [%d] : %s          ",chaine,*remaining,cache);    
        }
    } while ((*remaining)>0);
    printf("\n");
    return -1;
}


int main()
{
    int delay = 20;  // 20 secondes
    int res = timeoutgetnb(&delay,"Entrez nombre");
    printf("Resultat : %d\n",res);
    return 0;
}



Explanations

	No explanations yet.