Fully Abusing the scanf() Function

It’s sad but understandable that most C programmers use the scanf() function in a limited capacity. True, the function is dorky, so I accept any aversion to its use. It can also be abused to pose a security risk. Still, for “research purposes,” it’s entertaining to see how much the function can be twisted and torqued.

The key, introduced in last week’s Lesson, is to abuse the format string. Consider the following code:

2020_09_05-Lesson-a.c

#include <stdio.h>

int main()
{
    char a,b,c;

    printf("Type 'cat': ");
    scanf("%c%c%c",&a,&b,&c);
    printf("Got it: %c%c%c\n",a,b,c);

    return(0);
}

The scanf() function at Line 8 thirsts for three single-character values, each one typed one after the other. This input isn’t a string, as its assigned to three char variables, a, b, and c. And, of course, you need not type cat for input, as the following sample run demonstrates:

Type 'cat': dog
Got it: dog

The next example is a wee bit more practical, though don’t get too excited:

2020_09_05-Lesson-b.c

#include <stdio.h>

int main()
{
    char name[16];
    int score;

    printf("Enter your name and score: ");
    scanf("%s %d",name,&score);
    printf("%s scored %d\n",name,score);

    return(0);
}

The scanf() statement at Line 9 desires two separate input items, a string and an integer value (in decimal) separated by a space. These two input items must be typed properly, and you pray that string input doesn’t exceed 16 characters, or the code does all sorts of ugly things. Sample run:

Enter your name and score: Danny 1000000
Danny scored 1000000

True, it’s possible for scanf() to read more than one word in a string, providing you specify the spaces and other delimiting characters in the input format argument, as this code demonstrates:

2020_09_05-Lesson-c.c

#include <stdio.h>

int main()
{
    char first[16];
    char last[16];

    printf("Enter your name, first last: ");
    scanf("%s %s",first,last);
    printf("Hello, %s %s\n",first,last);

    return(0);
}

At Line 9, the scanf() function demands two words as input, separated by a space. Remember that for scanf(), string input is terminated by the first whitespace character encountered. By including the space character in the format string, you allow this specific whitespace character to flow in as input and not mess up everything. Here’s the obedient sample run:

Enter your name, first last: Danny Gookin
Hello, Danny Gookin

I have one more scanf() trick to show, covered in new week’s Lesson.

Leave a Reply