That’s Not the Input I Asked For

I recently had a reader submit a question regarding input. He wanted to write code that would read a character and display that character’s ASCII code value. It sounds like a simple program, but you must understand variable types and the scanf() function’s peculiarities to properly code it.

Here is his code:

#include <stdio.h>

int main()
{
    int test;

    scanf("%d",&test);
    printf("%d\n",test);

    return(0);
}

And here is sample output (keeping in mind that the code displays no prompts):

y
1770414134

The value 1770414134 is what I see on my Mac. On the PC the value is 57, but 57 also shows up when I type z instead of y. I assume different computers would generate different results. Of course, I believe that the programmer was expecting to see the ASCII code value for the character; letter 'y' is ASCII code 121 or 0x79.

The problem with the code is the scanf() function, which expects to read an integer, not a character:

scanf("%d",&test);

Variable test is an int variable. The %d (integer) placeholder in the scanf() function is set properly. In fact, the code is correct. If you compile, run, and input the value 121, you get:

121
121

The value 121 is stored in variable test. It works!

If you want to input a character, however, you must direct the scanf() function to look for a character. That means declaring test as a char variable and replacing the %d with a %c, the char placeholder. Here is the modified code:

#include <stdio.h>

int main()
{
    char test;

    scanf("%c",&test);
    printf("%d\n",test);

    return(0);
}

And when run:

y
121

While his is a common mistake made by anyone learning C, the weird output piqued my curiosity regarding how the character 'y' could be interpreted as value 1770414134? What’s even more puzzling to me is that the value changed each time I ran the code; the output was never the same!

The reason is simple: In the original code, the scanf() function is directed to read integer input. The character 'y' isn’t a numeric value, to input isn’t read. Therefore, variable test is never initialized. The result you see is whatever garbage is in memory at variable test‘s location.

To prove that variable test is uninitialized, I modified the original code to initialize it:

#include <stdio.h>

int main()
{
    int test = 0;

    scanf("%d",&test);
    printf("%d\n",test);

    return(0);
}

In Line 5, variable test is initialized to zero. If my theory is correct, the value of test won’t change when 'y' is input.

Here’s a sample run:

y
0

I modified the code again, set test to 14, and the program’s output showed 14. That confirms that non-numeric input is ignored by scanf().

Bottom line: If you want to read a character, use a char variable and the %c placeholder in the scanf() function.

Leave a Reply