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
%dis expected), it'll return0—meaning zero variables got a valid value from this call. - If part of the input matches (say you type
12.3for an integer specifier), it'll return1because it grabbed the leading integer12and 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
nbe assigned?- If they type a float/double like
5.7:scanf_swill read the leading integer (5) and assign it ton, then stop at the decimal point. Songets a valid integer value here. - If they type something totally non-numeric (like
abcor!@#):scanf_scan't match any integer pattern, sonstays as whatever garbage value was in that memory spot before the call (uninitialized variables have unpredictable values).
- If they type a float/double like
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 types12.3, the.3is 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 anotherscanf_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
abcfirst: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 bufferTo fix this, you can flush the buffer after a failed
scanf_sby reading and discarding all characters until a newline:int c; while ((c = getchar()) != '\n' && c != EOF);
内容的提问来源于stack exchange,提问作者Bak1139

