Namespaces
Variants

std:: setbase

From cppreference.net
< cpp ‎ | io ‎ | manip
ヘッダーで定義 <iomanip>
/*unspecified*/ setbase ( int base ) ;

ストリームの数値基数を設定します。式 out << setbase ( base ) または in >> setbase ( base ) 内で使用されると、 base の値に応じて、ストリーム out または in basefield フラグを変更します:

8、10、16以外の base 値は basefield をゼロにリセットします。これは10進数出力とプレフィックス依存の入力に対応します。

目次

パラメータ

base - 基数フィールドの新しい値

戻り値

未指定の型のオブジェクトであり、以下の条件を満たすもの

  • 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)
{
    // 基数フィールドを設定
    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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 183 C++98 setbase std::ostream または std::istream 型のストリームでのみ使用可能 任意の文字ストリームで使用可能

関連項目

整数I/Oで使用される基数を変更する
(関数)
数値の基数を示す接頭辞を使用するかどうかを制御する
(関数)