Course contentsShow
← C
Lesson 422 of 1,2196. Arrays and StringsFree lesson

Scanning strings with `%s` and `scanf` limitations

Scanning strings with %s and scanf limitations

What you'll learn: How to read user input into a character array using scanf and why it behaves unexpectedly when it encounters a space.

Reading text with %s

To store a word from a user, we use the %s format specifier. Unlike reading an integer with %d, you do not need the ampersand (&) symbol when passing a character array to scanf. This is because the name of an array effectively acts as a pointer to its first memory address.

#include <stdio.h>

int main() {
    char name[20];

    printf("Enter your first name: ");
    // Note: No '&' before name
    scanf("%s", name); 

    printf("Hello, %s!\n", name);
    return 0;
}

The "Space" limitation

Imagine scanf is like a vacuum cleaner that only picks up solid objects but stops the moment it hits a gap. In C, the %s specifier reads characters until it encounters whitespace—this includes spaces, tabs, or new lines.

If you run the code above and type "Alice," the output will be "Hello, Alice!" But if you type "Alice Smith," the output will still just be "Hello, Alice!"

Why? Because scanf sees the space after "Alice" as a signal to stop reading. The "Smith" part isn't deleted; it actually stays behind in the input buffer (a temporary storage area), waiting to be picked up by the next input command. This often leads to bugs where your program seems to "skip" future questions because it’s still processing the leftover text from the first scan.

Buffer Overflows

Another danger is that scanf is "trusting." If your array is 20 characters long but the user types a 50-character word, scanf will keep writing data past the end of your array. This is called a buffer overflow and can crash your program or create security holes. While you can limit this by using %19s (telling it to stop after 19 characters to leave room for the null terminator), standard scanf is generally considered unsafe for professional applications where users might enter unpredictable text.

Key takeaway

The %s specifier with scanf only reads a single word and stops at the first space, making it unsuitable for reading full sentences or names with spaces.