scanf
function family is not able to perform complex regex.
But it has some capability. If you want to read the first number entered by user, you can use:
%[0-9]
reads only a number (warning its 0-9
, not 9-0
)
%[^0-9]
reads all but a number
%*[^0-9]
reads all but a number and ignore it.
So you can write:
/* A simple scanset example */
#include <stdio.h>
int main(void)
{
char str[128];
int ret;
printf("Enter a string: ");
/* Try to read a number at input start */
ret = scanf("%[0-9]", str);
if (1 != ret){
/* if reading failed, try to re-read the input,
ignoring all that is before the number */
ret = scanf("%*[^0-9]%[0-9]", str);
}
if (1 != ret)
printf("no match");
else
printf("You entered: %s\n", str);
return 0;
}
As pointed in comments, this code can be better if read size is limited:
%8[0-9]
will limit scanf
to read only 8 numeric characters.
#include <stdio.h>
int main(void)
{
char str[8+1];
int ret;
printf("Enter a string: ");
/* Try to read a number at input start */
ret = scanf("%8[0-9]", str);
if (1 != ret){
/* if reading failed, try to re-read the input,
ignoring all that is before the number */
ret = scanf("%*[^0-9]%8[0-9]", str);
}
if (1 != ret)
printf("no match");
else
printf("You entered: %s\n", str);
return 0;
}
But in this code, you will have to handle a new fact: if the user enter a too big number, how to handle it? (strlen
can help, or strto[u]l
...)
Enter a string: 1234567891011
You entered: 12345678