C++ 使用扫描输入

C++ input with scanf

本文关键字:扫描输入 C++      更新时间:2023-10-16

我的控制台输入有问题。当我使用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