std::stoi

提供: C++入門
2014年8月27日 (水) 16:26時点におけるDaemon (トーク | 投稿記録)による版 (ページの作成:「std::stoi とは、文字列を数値に変換する関数です。10進数、16進数、8進数などの文字列を整数(int)に変換できます。C言語で...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索
スポンサーリンク

std::stoi とは、文字列を数値に変換する関数です。10進数、16進数、8進数などの文字列を整数(int)に変換できます。C言語で言えば、atoiやstrtolにあたります。atoiとの大きな違いは、std::stringをダイレクトに渡せることでしょう。atoiでは、std::stringを直接渡せないため、c_str()の呼び出しが必要です。

読み方

std::stoi
えすてぃーでぃー えす とぅー あい

概要

std::stoiは、std::stringか、std::wstringを扱えます。第3引数で基数を指定できます。 第3引数に0を指定した場合、基数が自動的に選択されます。

  • 先頭が0の場合は、8進数
  • 先頭が0xもしくは、0Xの場合は、16進数

std::stoiのファミリには、以下のシリーズがあります。

  • long std::stol
  • long long std::stoll
  • unsigned long std::stoul
  • unsigned long long std::stoull
  • float std::stof
  • double std::stod
  • long double std::stold

プロトタイプ

namespace std {
  int stoi(const string& str, size_t* idx = nullptr, int base = 10);
  int stoi(const wstring& str, size_t* idx = nullptr, int base = 10);
}

例外

  • 数値への変換が行われない場合は、std::invalid_argument が送出されます。
  • 範囲外の値になった場合は、std::out_of_rangeが送出されます。

文字列を整数に置き換える例 stoi1.cpp

文字列(10進数形式、8進数形式、16進数形式)を整数に変換する例です。

ソースコード stoi1.cpp

/*
 * stoi1.cpp
 * Copyright (C) 2014 kaoru <kaoru@bsd>
 */
 
#include <iostream>
#include <string>
 
using namespace std;
 
int
main(int argc, char const* argv[])
{
        string d10 = "10";      // 10進数
        string o80 = "010";     // 8進数
        string xFF = "0xFF";    // 16進数
        string FF = "FF";       // 16進数, 0xなし
        int a = std::stoi(d10); // 10進数
        int b = std::stoi(o80, nullptr, 8);     // 8進数
        int c = std::stoi(xFF, nullptr, 16);    // 16進数
        int d = std::stoi(FF, nullptr, 16);     // 16進数, 0xなし
        cout << a << endl;
        cout << b << endl;
        cout << c << endl;
        cout << d << endl;
        return 0;
}

コンパイル

c++  stoi1.cpp -o stoi1

実行例

% ./stoi1
10
8
255
255

例外を送出する例 stoi2.cpp

ソースコード stoi2.cpp

/*
 * stoi2.cpp
 * Copyright (C) 2014 kaoru <kaoru@bsd>
 */
#include <iostream>
#include <string>
 
using namespace std;
 
int
main(int argc, char const* argv[])
{
        try {
                int a = std::stoi("hoge");
        } catch (std::invalid_argument e) {
                cout << e.what() << endl;
        } catch (std::out_of_range e) {
                cout << e.what() << endl;
        }
 
        try {
                int a = std::stoi("999999999999");
        } catch (std::invalid_argument e) {
                cout << e.what() << endl;
        } catch (std::out_of_range e) {
                cout << e.what() << endl;
        }
 
        return 0;
}

コンパイル

c++  stoi2.cpp -o stoi2

実行例

% ./stoi2
stoi: no conversion
stoi: out of range

関連項目




スポンサーリンク