[英]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
类型为std::istream
(一个类),已实现了operator>>
。 当您这样做时:
cin >> n;
它被翻译为:
cin.operator>>(n);
其中n
作为int&
传递
scanf("%c")
和operator>>
之间有根本的区别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相反:
匹配非空格字符序列(字符串)
空格是一个字符。 这也是一个空白字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.