我试图比较 std::cin
和 scanf
,我希望它们有相同的行为,但实际上不是:
#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);
让我们阅读 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);
关于c++ - Scanf 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38013209/