scanf读取异常:输入month后total值异常,为何%s失效而%c可行?
%s Broke Your total Variable, and %c Fixed It Hey there! Let's break down exactly what was happening here, step by step.
First: The Core Difference Between char and Strings in C
Your variable month is declared as a single char—that's just 1 byte of memory, meant to hold one character (like 'J' for January). But the %s format specifier in scanf is designed to read strings, which in C are sequences of characters ending with a null terminator (\0, a byte with value 0).
Why %s Messed Up total
When you used scanf("%s", &month), here's what went wrong:
- Suppose you entered something like "Jan" for the month.
scanftries to write the entire string into the memory starting at&month. - But
monthonly has 1 byte of space. After writing the first character ('J') intomonth,scanfkeeps writing the next characters ('a', 'n') and the required null terminator (\0) into the memory right aftermonth. - On most systems, local variables (like
totalandmonth) are stored close together on the stack. In your case,totalwas sitting in the memory immediately aftermonth. Those extra bytes written by%soverwrote part oftotal's memory, turning its value into that random-looking number 28257 (that's just the ASCII values of the extra characters interpreted as an integer).
Why %c Works
The %c format specifier is made for reading a single character. When you use scanf(" %c", &month) (the leading space skips any leftover whitespace like newlines from the previous scanf), it only writes one byte into month's memory. No extra bytes get written, so total's memory stays untouched—no more weird value changes.
A Quick Extra Tip
If you actually wanted to read full month names (like "January") instead of single characters, you'd need to declare month as a character array, e.g., char month[20]; (to hold up to 19 characters plus the null terminator). Then you could safely use %s to read into it, as long as you make sure the array is big enough for the input.
内容的提问来源于stack exchange,提问作者Dan Tang

