scanf family functions support scanset specifiers which are represented by %. Inside scanset, we can specify single character or range of characters. While processing scanset, scanf will process only those characters which are part of scanset. We can define scanset by putting characters inside squre brackets. Please note that the scansets are case-sensitive.
Let us see with example. Below example will store only capital letters to character array ‘str’, any other character will not be stored inside character array.
[root@centos-6 C]# ./scan-set Enter a string: GEEKs_for_geeks You entered: GEEK
If first character of scanset is ‘^’, then the specifier will stop reading after first occurrence of that character. For example, given below scanset will read all characters but stops after first occurrence of ‘o’
Let us see with example.
[root@centos-6 C]# ./scan-set Enter a string: http://geeks for geeks You entered: http://geeks f [root@centos-6 C]#
Let us implement gets() function by using scan set. gets() function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF found.
[root@centos-6 C]# ./gets Enter a string with spaces: Geeks For Geeks You entered: Geeks For Geeks [root@centos-6 C]#
As a side note, using gets() may not be a good idea in general. Check below note from Linux man page.
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. Also see this post.
This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Strict Aliasing Rule in C with Examples
- Difference between C and Dart
- Difference between Sentinel and Counter Controlled Loop in C
- Why do we need reference variables if we have pointers
- What are the differences between C and Embedded C?
- Macros and its types in C/C++
- Draw a smiley face using Graphics in C language
- NULL undeclared error in C/C++ and how to resolve it
- Draw a Chess Board using Graphics Programming in C
- Which will be faster while(1) or while(2)?
- what happens when you don't free memory after using malloc()
- Average of Cubes of first N natural numbers
- Top 10 Programming Languages for Blockchain Development
- How many levels of pointers can we have in C/C++