c++ - Scanf 没有按预期工作

标签 c++ scanf cin

我试图比较 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);

让我们阅读 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/

相关文章:

c++ - 在使用 cin 请求 int 时如何有效地防止用户输入?

c++ - 如何清除 cin 的缓冲区?

c# - 如何处理由 C++ 加载的 C# DLL 中的异常

c++ - 是否可能存在不会导致程序崩溃的内存问题?

assembly - sscanf 是如何工作的? ( assembly 中)

c - 使用scanf c编程从文本文件中读取十进制数

c - 这个C程序有什么问题吗? (使用scanf从终端扫描)

c++ - 获取多行输入以在 C++ 中进行解析

c++ - Qt5 和 OpenCV 4

c++ - 'sizeof' 对不完整类型的无效应用(创建的类)