簡體   English   中英

使用scanf的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類型為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相反:

匹配非空格字符序列(字符串)

空格是一個字符。 這也是一個空白字符。

來源: http//en.cppreference.com/w/cpp/io/c/fscanf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM