Scanset in C

The %[] symbol denotes a scanset specifier that is supported by the scanf family of functions. You can provide a single character or a range of characters inside the scanset. Only characters that are a part of the scanset will be processed by the scanf() function during processing. You can define scanset by enclosing characters in square brackets.

By using a comma between the desired character and the scanset, you may also use this method.

For example:

It will scan every character in the scanset that is supplied. Let's see the scanset by using an example. In the example below, the character array 'str' will only hold capital letters; any other characters will not be kept there.

Example 1:

Character matching with specifics:

Let's say you wish to read a numeric input (0 to 9) alone. It would be a scanset of %[0-9]. Here's an illustration:

Output:

Enter a number: 12345
You entered: 12345

Example 2:

Matching alphabetic characters:

You can use %[a-zA-Z] to read a string that only contains alphabetic characters (a to z and A to Z). Here's an instance:

Output:

Enter a word: javatpoint
You entered: javatpoint

Example 3:

Matching a set of characters precisely:

Within the scanset, you can define several characters to match. For instance, you can use %[0-9A-Z] to read a string that only contains uppercase letters and digits. Here's an illustration:

Output:

Enter a string (digits and uppercase letters only): HELLO1234
You entered: HELLO1234

Example 4:

Until a certain character is found, characters are matched:

You can use the symbol at the start of the scanset to reverse the matching behavior. It will continue reading till it comes across the requested character. For instance, you can use %['n'] to read a string up until a newline character is found.

Output:

Enter a sentence (ends with Enter key): Hello world!
You entered: Hello world!

Example 5:

Let's use the scanset to implement the gets() function. The gets() method reads lines from the standard input (stdin) into the buffer pointed to by scanset until a terminating newline or EOF is detected.

Output:

Enter a string with spaces: hello world
You entered: hello world

Note: Never use the gets() method. Gets() will keep storing characters after the end of the buffer, making it hard to predict how many characters it will read without knowing the data in advance. It has been utilized to circumvent computer security. In its place, use the fgets() function.






Latest Courses