Course contentsShow
← C
Lesson 698 of 1,21910. Input and OutputFree lesson

Using scansets with %[...]

Using scansets with %[...]

What you'll learn: How to use scansets in scanf() to limit input to specific characters and handle spaces safely.

Standard scanf("%s", ...) has a annoying habit: it stops reading the moment it hits a space. If you try to type "New York," it only captures "New." To fix this without jumping to more complex functions, we use scansets.

The "VIP List" for Characters

Think of a scanset like a security guard at a club holding a clipboard. The %[...] format specifier tells scanf exactly which characters are allowed to enter your variable. The moment the user types a character that isn't on the list, the "guard" closes the door and stops reading.

For example, %[abcd] will only accept the letters a, b, c, or d. If the user types "abccde," the variable will store "abcc" and stop at the 'e'.

Capturing Spaces

The most common use for scansets is reading strings that include spaces. By using the "caret" symbol (^), you can tell scanf to accept everything except a specific character. Usually, we tell it to accept everything until it hits a newline (\n).

#include <stdio.h>

int main() {
    char fullName[50];

    printf("Enter your full name: ");
    
    // The [^\n] means "read everything until you hit a Enter/Newline"
    // The 49 limits the length to prevent crashing (leaving 1 for the null terminator)
    scanf("%49[^\n]", fullName);

    printf("Hello, %s!\n", fullName);

    return 0;
}

Why this is safer

In the code above, %49[^\n] does two important jobs:

  1. It handles spaces: Unlike %s, it won't quit when it sees a space between a first and last name.
  2. It prevents overflows: By including the number 49, we ensure that if a user types a 100-character name, our program won't crash; it will simply stop at the 49th character.

You can also use ranges, like %[a-z] to only accept lowercase letters, or %[0-9] for digits. It is a powerful, built-in filter that keeps "trash" data out of your variables from the very start.

Key takeaway

Scansets (%[...]) allow you to define a specific whitelist or blacklist of characters for input, making it easy to read full lines of text including spaces.