Huzo
Huzo

Reputation: 1692

Accepting empty inputs with scanf() in C

I want to read two digit entered by the user. But the thing is that user may enter just 1 number too. So the list of inputs could be like this:

1  2
2
4  2
15

It is a simple question but I could not find the exact problem asked. Most of the problems ask for an empty string input but it is a case of integers now.

Thanks

Upvotes: 0

Views: 1195

Answers (1)

user2736738
user2736738

Reputation: 30926

scanf is for formatted input output. This doesn't go with you requirement. Just as being mentioned use fgets to read the whole line and then parse the number inputted by using something like strtol etc.

#define MAXLEN 60
....
char pp[MAXLEN+1];
if(fgets(pp,MAXLEN+1,stdin) == NULL ){
    fprintf(stderr,"Error in input");
    exit(EXIT_FAILURE);
}

char *ptr = pp;
char *end;
errno = 0;
long i = strtol(ptr, &end, 10);
while( ptr != end )
{
    ptr = end;
    if (errno == ERANGE){
        printf("range error, got ");
        errno = 0;
    }
    printf("Got - %ld\n", i);
    /* work with i */
    i = strtol(ptr, &end, 10);
}

Demo of the code here.

Upvotes: 2

Related Questions