How can we use scanset to restrict any character input from user ?

We can restrict or allow any character set for user input using scanset  %[].

Consider this example :-

#include <stdio.h>
int main()
{
char str[20];
printf("Enter any String : ");
scanf("%[a-z]",str);
printf("String you entered is : %s",str);

return 0;
}

In this program, user input is taken with the help of scanset and it allows only small case characters as input. This means, if user enters any character other than small case characters [a to z], scanf() terminates scanning and only valid part is assigned as input. For example, consider these two outputs :-

Output 1

Enter any String : programmingprashn
String you entered is : programmingprashn

Here, all are small case characters, therefore all characters are scanned and stored in str successfully.

Output 2

Enter any String : programmingPrashn
String you entered is : programming

Here, scanf() stops scanning when it encountered 'P', as it does not belongs to the scanset i.e. [a-z].


There are some more examples of the scanset below: