Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Scansets in C
Scansets in C are special format specifiers supported by the scanf() family of functions. They allow you to specify which characters to accept or reject when reading input. Scansets are represented by %[] and provide fine-grained control over input validation.
Syntax
%[characters] // Accept only specified characters %[^characters] // Accept all characters except specified ones %[character-range] // Accept characters within a range
Example 1: Basic Character Set
This example demonstrates how to read only uppercase letters using a character range −
#include <stdio.h>
int main() {
char str[50];
printf("Enter something: ");
scanf("%[A-Z]", str);
printf("Given String: %s<br>", str);
return 0;
}
Enter something: HElloWorld Given String: HE
The scanset %[A-Z] stops reading when it encounters the first lowercase letter 'l'. Only uppercase characters before that point are captured.
Example 2: Negated Scanset
When the scanset begins with ^, it reads all characters except those specified −
#include <stdio.h>
int main() {
char str[50];
printf("Enter something: ");
scanf("%[^r]", str);
printf("Given String: %s<br>", str);
return 0;
}
Ent Analyzing the existing text: - It explains scansets clearly but has some formatting issues - The code examples are good but use incorrect HTML formatting - Missing proper syntax section - Needs better structure and conclusion - The second example explanation could be clearer I'll improve the structure, fix the HTML formatting, and enhance explanations while keeping the core content intact. <pre class="result notranslate"> Enter something: HelloWorld Given String: HelloWo
The scanset %[^r] reads all characters until it encounters 'r', which stops the input processing.
Example 3: Reading Strings with Spaces
A common use case is reading entire lines including spaces by excluding only the newline character −
#include <stdio.h>
int main() {
char str[100];
printf("Enter something: ");
scanf("%[^<br>]", str);
printf("Given String: %s<br>", str);
return 0;
}
Enter something: Hello World. This line has some spaces. Given String: Hello World. This line has some spaces.
Key Points
- Scansets are case-sensitive and process characters sequentially
- Reading stops at the first character that doesn't match the scanset criteria
- The
^symbol inverts the scanset logic (exclude instead of include) - Always ensure your buffer size is adequate to prevent overflow
Conclusion
Scansets provide powerful input filtering capabilities in C, allowing precise control over which characters are accepted. They are particularly useful for input validation and reading formatted text data.
