scanf 参数的差异

difference in scanf parameters

我写程序的时候,不注意scanf的参数。 有什么区别:

scanf("%d %d", &x,&y);

scanf("%d%d", &x,&y);

注意 %d 之间的 space。 我在我的电脑上试过了,但我看不出有什么不同。

此外,%c 而不是 %d -

之间有什么区别
scanf("%c %c", &x,&y);

scanf("%c%c", &x,&y);

你能给我一些有用的例子来理解这个愚蠢的东西吗?

在你的情况下,无论你是否在两者之间放置 space,它们都会产生相同的结果 :)

来自cppreference

All conversion specifiers other than [, c, and n consume and discard all leading whitespace characters (determined as if by calling isspace) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.

The conversion specifiers that do not consume leading whitespace, such as %c, can be made to do so by using a whitespace character in the format string:

scanf("%d", &a);
scanf(" %c", &c); // ignore the endline after %d, then read a char

所以你的例子:scanf("%c%c", &x, &y);不会跳过白色space。
如果您输入 a b 后跟回车,它将显示为 a 和一个白色的 space.
另一方面,如果您输入 ab,它将根据您的需要读取 a 和 b。

在例子中:scanf("%c %c", &x, &y);,如果你输入a然后回车,它会忽略换行,让你输入另一个字符。

scanf("%d %d", &x, &y) 将在读取第一个整数后吃掉 space (如果有),然后读取第二个整数,而 scanf("%d%d", &x, &y) 将在读取时忽略 whitespace两个整数。但是,当 运行.

时,两者都会产生相同的结果

匹配空格的格式指令(例如 isspace returns 为真的任何内容)导致从流中读取和丢弃尽可能多的空格(stdin,在这种情况)。

无论如何,在 %d 格式指令转换数字之前需要这个过程;也就是说,%d 指令将读取并丢弃尽可能多的空格,然后读取符号 and/or 十进制数字序列并将其转换为 int.

总而言之,不管有没有 whitespace 指令,这两个语句的功能都是一样的;在这种情况下,空格指令是多余的。