Scanf 没有按预期工作

Scanf does not work as expected

我试图比较 std::cinscanf,我希望它们具有相同的行为,但实际上不是:

#include<iostream>
using namespace std;
int main()
{
  int i;
  cin>>i;
  return 0;
}

这会收到用户的输入,没问题。 但是

#include<stdio.h>
int main()
{
  int i;
  scanf("%d\n",&i);
  return 0;
}

我输入了一个整数,即使我多次按"enter"程序也不会终止,除非我输入另一个整数。

请注意,scanf 的格式字符串中有一个“\n”。 所以我尝试添加一个语句

printf("%d\n", i);

嗯,它打印出我刚刚输入的第一个数字。这是正确的但很奇怪,为什么在 scanf 之后,程序要求我输入任何字符而不是 \n 来退出程序?

我试过 VC 和 GCC,同样的问题。 \n 表示什么?

scanf("%d\n",&i); 等同于 std::cin >> i >> std::ws;.

如果您希望 scanf 具有相同的行为,请删除 \nscanf("%d",&i);

这是因为 scanf 中的任何空白字符都表示 "skip input until non-whitespace is found"

  scanf("%d\n",&i);

让我们阅读manpage of scanf :

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

这意味着 scanf 将搜索后跟可选空格的整数。这就是为什么他在等你使用两次输入。如果你用了"%d\n\n",那就得三遍了。等等。

如果您只想要一个整数,请使用 scanf("%d",&i);