C++ ios::Boolalpha() 函式



C++ 的std::ios::boolalpha函式用於控制流中布林輸出的格式。當呼叫此函式時,布林值將顯示為文字 true 或 false,而不是預設的 1 或 0。它透過使用 std::boolalpha 操縱器觸發,並使用 std::noboolalpha 停用。

此函式提高了日誌和使用者介面中布林輸出的可讀性。

語法

以下是 std::ios::boolalpha() 函式的語法。

ios_base& boolalpha (ios_base& str);

引數

  • str - 它表示其格式標誌受影響的流物件。

返回值

此函式返回引數 str。

異常

如果丟擲異常,則 str 處於有效狀態。

資料競爭

它修改了 str。併發訪問同一個流物件可能會導致資料競爭。

示例

在以下示例中,我們將考慮 boolalpha() 函式的基本用法。

#include <iostream>
int main()
{
    bool x = true;
    std::cout << "Without boolalpha: " << x << std::endl;
    std::cout << std::boolalpha;
    std::cout << "With boolalpha: " << x << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

Without boolalpha: 1
With boolalpha: true

示例

考慮以下示例,我們將使用 boolalpha 與 std::cin 從使用者讀取布林值。

#include <iostream>
int main()
{
    bool x;
    std::cout << "Enter true or false : ";
    std::cin >> std::boolalpha >> x;
    std::cout << "Entered Input : " << x << std::endl;
    return 0;
}

輸出

以下是以上程式碼的輸出:

Enter true or false : true
Entered Input : 1

示例

讓我們看一下以下示例,我們將確定給定數字是偶數還是奇數。

#include <iostream>
int main()
{
    bool x = false;
    int a = 1;
    if (a % 2 == 0) {
        x = true;
    }
    std::cout << std::boolalpha;
    std::cout << "Is the given number even? " << x << std::endl;
    return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Is the given number even? false
ios.htm
廣告

© . All rights reserved.