名稱空間
變體
操作

std::setbase

來自 cppreference.com
< cpp‎ | io‎ | manip
 
 
 
輸入/輸出操縱器
浮點格式化
整數格式化
布林格式化
欄位寬度和填充控制
其他格式化
空白字元處理
輸出重新整理
(C++20)  

狀態標誌操作
時間與金錢 I/O
(C++11)
(C++11)
(C++11)
(C++11)
帶引號的操縱器
(C++14)
 
定義於標頭檔案 <iomanip>
/*未指定*/ setbase( int base );

設定流的數字基數。當在表示式 out << setbase(base)in >> setbase(base) 中使用時,根據 base 的值,更改流 outinbasefield 標誌。

除了 8、10 或 16 之外的 base 值會將 basefield 重置為零,這對應於十進位制輸出和字首依賴的輸入。

目錄

[編輯] 引數

base - basefield 的新值

[編輯] 返回值

一個未指定型別的物件,使得

  • 如果 out 是型別 std::basic_ostream<CharT, Traits> 的物件,則表示式 out << setbase(base)
    • 型別為 std::basic_ostream<CharT, Traits>&
    • 值為 out
    • 其行為如同呼叫了 f(out, base)
  • 如果 in 是型別 std::basic_istream<CharT, Traits> 的物件,則表示式 in >> setbase(base)

其中函式 f 定義為

void f(std::ios_base& str, int base)
{
    // set basefield
    str.setf(base == 8 ? std::ios_base::oct :
        base == 10 ? std::ios_base::dec :
        base == 16 ? std::ios_base::hex :
        std::ios_base::fmtflags(0), std::ios_base::basefield);
}

[編輯] 示例

#include <iomanip>
#include <iostream>
#include <sstream>
 
int main()
{
    std::cout << "Parsing string \"10 0x10 010\"\n";
 
    int n1, n2, n3;
    std::istringstream s("10 0x10 010");
 
    s >> std::setbase(16) >> n1 >> n2 >> n3;
    std::cout << "hexadecimal parse: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
 
    s.clear();
    s.seekg(0);
 
    s >> std::setbase(0) >> n1 >> n2 >> n3;
    std::cout << "prefix-dependent parse: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
 
    std::cout << "hex output: " << std::setbase(16)
              << std::showbase << n1 << ' ' << n2 << ' ' << n3 << '\n';
}

輸出

Parsing string "10 0x10 010"
hexadecimal parse: 16 16 16
prefix-dependent parse: 10 16 8
hex output: 0xa 0x10 0x8

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 183 C++98 setbase 只能用於流
型別為 std::ostreamstd::istream
可用於任何
字元流

[編輯] 另請參閱

更改整數 I/O 所用的基數
(函式) [編輯]
控制是否使用字首指示數字基數
(函式) [編輯]