为什么在添加 space 或新行后第二个变量的值无关紧要?

Why value of second variable is irrelevant after adding space or new line?

我是编程学习C的新手language.I有点迷茫对吧now.I尝试Google但是找不到满意的结果所以我想排序在这个网站上提问。
看看这个小程序

#include<stdio.h>
int main()
{
    int num1,num2;
    printf("enter the value of num1 and num2:");
    scanf("%d %d",&num1,&num2);
    printf("num1 = %d and num = %d",num1,num2);
    return 0;
}

当我输入值时 例如 - 215-15 没有 spacenew line 比它给出输出 num1 = 215num2 = -15 但是当我在 215- 和 [= 之间输入 spacenew line 时23=]15 然后它给出输出 num1 = 215num2 = -175436266(或任何意外的数字)。

我知道当 scanf() 读取任何不在转换规范类别中的字符时,它会放回该字符并结束处理其他 inputs.But 在第一种情况下 -(minus sign) 似乎是根据转换规范不相关的输入但它显示正确的输出但在后一种情况下它不显示正确 output.Why?

因为 215- 15 只能匹配一个数字:215。一旦 scanf() 读取到 -,它就会停止处理第一个匹配项,因为 - 不能可能是当前号码的数字,所以 num1 匹配 215.

然后,没有更多的数字可以匹配,因为你剩下 - 15scanf() 读取一个 - 后跟一个 space,因此没有要解析的有效数字,它 returns(推回 space 和破折号之后).它没有为 num2 分配任何内容,所以当你打印它时你看到的是垃圾。

那么,为什么它适用于 215-15

space 与众不同。使用 215-15scanf() 再次将第一个数字与 215 匹配,但现在您在输入中留下 -15(而不是前面示例中的 - 15)。 -15 在符号和数字的第一位之间没有 space,因此 scanf() 将其视为有效数字,并成功解析它。

简而言之,在这两个示例中,- 都被解释为下一场比赛的号码符号。但是 %d 不会忽略数字数字之间或符号与数字之间的白色 space 字符(尽管它会忽略任何数量的白色 space 之前 数字开始 - 即在第一个数字之前或符号之前)。因此,如果它看到 - 后跟 space,它就会失败。如果它看到 - 后跟一个或多个数字,则它会成功匹配一个数字,并使用这些数字直到找到一个不是数字的字符。

我认为正在发生的事情在 cplusplus.com 的 scanf 参考资料中有所描述。

Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

此外,

A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

scanf 的格式字符串是“%d %d”。它需要一个数字,它会丢弃空格和另一个数字。在第一个数字之后,读取的“-”字符与格式说明符不匹配,因此 scanf 提前失败,使 num2 变量未初始化。

如果检查 scanf 的 return 值,它将失败。