簡體   English   中英

cout 中的異常行為。 在聲明另一個相同值的字符數組后打印兩次字符數組

[英]abnormal behaviour in cout. It is printing twice character array after declaration of another same valued character array

所以我正在編寫代碼以在 c++ 中打印字符數組。 正常代碼是:-

#include <iostream>
using namespace std;

int main()
{
    char X[5] = {'A', 'B', 'C', 'D', 'E'};
    cout << X << endl;
    return 0;
}

它正在打印:- ABCDE正如預期的那樣,但我試圖創建另一個像這樣的字符數組

#include <iostream>
using namespace std;

int main()
{
    char X[5] = {'A', 'B', 'C', 'D', 'E'};
    char Y[5] = {'A', 'B', 'C', 'D', 'E'};
    cout << X << endl;
    return 0;
}

我以為我會得到相同的 output 但它沒有發生。 output 是ABCDEABCDE我不明白為什么會這樣。
那時我正在電腦上編碼。 所以,我訪問了在線 c++ 編譯器,仍然得到相同的結果。
請任何人幫助我理解它為什么會發生? 我在我的電腦上使用 C++14。 這是我重新檢查代碼的在線編譯器網站的鏈接。

行為未定義。

std::ostreamconst char*重載(由於指針衰減而選擇),在達到 NUL 之前不會停止輸出。

因此,在 arrays 中包含 NUL 終止符是解決方法:

char X[/*let the compiler do the counting*/] = {'A', 'B', 'C', 'D', 'E', 0};

&C。

暫無
暫無

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

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