You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

scanf读取异常:输入month后total值异常,为何%s失效而%c可行?

Understanding Why %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. scanf tries to write the entire string into the memory starting at &month.
  • But month only has 1 byte of space. After writing the first character ('J') into month, scanf keeps writing the next characters ('a', 'n') and the required null terminator (\0) into the memory right after month.
  • On most systems, local variables (like total and month) are stored close together on the stack. In your case, total was sitting in the memory immediately after month. Those extra bytes written by %s overwrote part of total'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:23:37