C++ 使用扫描输入
C++ input with scanf
我的控制台输入有问题。当我使用cin
时,它可以完美地工作,但是当我使用scanf
它不起作用时。我删除了所有不重要的东西,这是程序:
#include <bits/stdc++.h>
using namespace std;
int n;
char c, t;
char a[81][81];
int main()
{
cin >> n;
for(int i = 0;i < n; ++i)
for(int j = 0;j < n; ++j)
{
scanf("%c", a[i][j]);
}
for(int i = 0;i < n; ++i)
for(int j = 0;j < n; ++j)
{
cout <<a[i][j] << " ";
}
return 0;
}
问题是,当我使用这样的输入对其进行测试时:
2
t t t t
它应该输出:
t t t t
但相反,它输出的是:
t t
您可以使用:
char c;
std::cin >> c;
并期望将值读入c
,因为该函数调用与对char
的引用一起工作。函数签名等效于:
std::istream& operator>>(std::istream& is, char& c);
然而
char c;
scanf("%c", c);
不起作用,因为scanf
需要一个指向char
的指针。因此,您必须使用;
scanf("%c", &c);
这对您的代码意味着什么?您必须使用:
scanf("%c", &a[i][j]);
你需要这个:
scanf("%c", &a[i][j]);
取而代之的是:
scanf("%c", a[i][j]);
为什么?
好吧,scanf
应该对您传递的变量(格式字符串除外)执行写入。在 C 语言中,只能通过指针来实现。因此,您需要传递a[i][j]
的地址
为什么它适用于cin>>
?好吧,C++引入了引用,并且n
传递为int&
而不仅仅是int
. cin
是已实现operator>>
的 std::istream
类型(类)。当您执行以下操作时:
cin >> n;
它被翻译为:
cin.operator>>(n);
n
作为int&
传递的位置
> scanf("%c")
和 operator>>
之间存在根本区别
这个程序演示了它:
#include <iostream>
#include <sstream>
int main()
{
std::cout << "with operator >>" << std::endl;
std::istringstream ss(" t t ");
char c;
while (ss >> c)
std::cout << "[" << c << "]" << std::endl;
std::cout << "with scanf" << std::endl;
auto str = " t t ";
for (int i = 0 ; i < 5 ; ++i)
{
char c;
if (sscanf(str + i, "%c", &c)) {
std::cout << "[" << c << "]" << std::endl;
}
}
}
预期输出:
with operator >>
[t]
[t]
with scanf
[ ]
[t]
[ ]
[t]
[ ]
请注意,operator>>
正在删除空格(这是 c++ std::basic_istream<>
的默认行为,可以禁用)。
请注意,sscanf
不会删除%c
运算符的空格。
从 %c 的文档:
匹配一个字符或一个字符序列
与 %s 相反:
匹配一系列非空格字符(字符串)
空格是一个字符。它也是一个空格字符。
来源: http://en.cppreference.com/w/cpp/io/c/fscanf
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++客户端/服务器聊天应用程序 - 从 Ubuntu 命令窗口扫描输入
- 如何通过用户输入扫描并将其切成C 的块
- 在数组中声明的字符串扫描用户输入
- C++ 使用扫描输入
- 如何扫描TXT文件并输入矩阵C
- C++ 如何扫描用户的字符串输入以查找特定单词/单词?
- 逐行扫描文件中的输入
- 扫描 读取格式化输入
- 如果图形以邻接表的形式给出,如何扫描用户输入