C++ ios::Showpos() 函式



C++ 的std::ios::showpos()函式是一個操縱器,它強制輸出流在正數前顯示加號(+)。它用於提高數值輸出的可讀性,尤其是在區分正值和負值時。

例如,std::cout << std::showpos << 112; 則輸出將為 +112。

語法

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

ios_base& showpos (ios_base& str);

引數

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

返回值

此函式返回引數 str。

異常

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

資料競爭

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

示例

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

#include <iostream>
int main()
{
    int x = 121;
    std::cout << std::showpos;
    std::cout << "Result :  " << x << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

Result :  +121

示例

考慮以下示例,我們將使用 showpos() 函式處理負數和正數。

#include <iostream>
int main()
{
    int x = 11;
    int y = -11;
    std::cout << std::showpos;
    std::cout << "Result : " << x << std::endl;
    std::cout << "Result : " << y << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

Result : +11
Result : -11

示例

在下面的示例中,我們將使用 showpos() 函式處理浮點數。

#include <iostream>
int main()
{
    double x = 11.23;
    std::cout << std::showpos;
    std::cout << "Result : " << x << std::endl;
    return 0;
}

輸出

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

Result : +11.23
ios.htm
廣告