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

scanf_s输入格式不匹配的返回值及输入异常对程序的影响咨询

Hey there, let's walk through these scanf_s questions clearly—they're super common gotchas in C, so I get why you're asking!

1. What's scanf_s's return value when input doesn't match the format?

scanf_s returns the count of successfully matched and assigned input items. So:

  • If you enter something that doesn't match the format at all (like a string when %d is expected), it'll return 0—meaning zero variables got a valid value from this call.
  • If part of the input matches (say you type 12.3 for an integer specifier), it'll return 1 because it grabbed the leading integer 12 and assigned it, leaving the rest of the input unread in the buffer.

2. Let's break down that specific scenario

You've got this code snippet:

printf("How many sides do the polygon has: ");
scanf_s("%d",&n);

Here's what happens when users enter non-integers:

  • Will variable n be assigned?

    • If they type a float/double like 5.7: scanf_s will read the leading integer (5) and assign it to n, then stop at the decimal point. So n gets a valid integer value here.
    • If they type something totally non-numeric (like abc or !@#): scanf_s can't match any integer pattern, so n stays as whatever garbage value was in that memory spot before the call (uninitialized variables have unpredictable values).
  • Does the invalid input only exist "in the background"?
    Nope. The unread part of the input stays in the input buffer. For example, if someone types 12.3, the .3 is left in the buffer waiting for the next input operation to pick it up.

  • Will this negatively affect subsequent program runs?
    Definitely. If you have another input function later (like another scanf_s, getchar, etc.), it'll read that leftover garbage instead of waiting for the user to type something new. This can make your program skip prompts, act unpredictably, or even get stuck in loops.

    For example, this code would break if the user enters abc first:

    int n;
    printf("How many sides do the polygon has: ");
    scanf_s("%d", &n);
    // User enters "abc"
    printf("Enter another number: ");
    int m;
    scanf_s("%d", &m); // This fails immediately because "abc" is still in the buffer
    

    To fix this, you can flush the buffer after a failed scanf_s by reading and discarding all characters until a newline:

    int c;
    while ((c = getchar()) != '\n' && c != EOF);
    

内容的提问来源于stack exchange,提问作者Bak1139

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:13:23