std::setbase
來自 cppreference.com
定義於標頭檔案 <iomanip> |
||
/*未指定*/ setbase( int base ); |
||
設定流的數字基數。當在表示式 out << setbase(base) 或 in >> setbase(base) 中使用時,根據 base 的值,更改流 out 或 in 的 basefield
標誌。
- 值 16 將
basefield
設定為 std::ios_base::hex。 - 值 8 將
basefield
設定為 std::ios_base::oct。 - 值 10 將
basefield
設定為 std::ios_base::dec。
除了 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)
- 型別為 std::basic_istream<CharT, Traits>&
- 值為 in
- 其行為如同呼叫了 f(in, 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::ostream 或 std::istream |
可用於任何 字元流 |
[編輯] 另請參閱
更改整數 I/O 所用的基數 (函式) | |
控制是否使用字首指示數字基數 (函式) |