LoginSignup
15
14

More than 5 years have passed since last update.

[C++11~] std::stoi で文字列を数値に変換する

Last updated at Posted at 2017-03-21

C++11から文字列から数値への変換の標準ライブラリとして、std::stoiが存在します。
std::stoiではC言語のatoiなどと違いstd::stringをそのまま取り扱うことができます。

例外

  • 変換できない形式の文字列が指定された => std::invalid_argument
  • 範囲外の値が指定された => std::out_of_range

実装例

使用例
#include <iostream>
#include <string>
#include <stdexcept>

int main(int argc, char* argv[]) {
    for (int i = 1; i < argc; ++i) {
        try {
            int num = std::stoi(argv[i]);
            std::cout << "[" << i << "]: " << num << std::endl;
        }
        catch (const std::invalid_argument& e) {
            std::cout << "[" << i << "]: " << "invalid argument" << std::endl;
        }
        catch (const std::out_of_range& e) {
            std::cout << "[" << i << "]: " << "out of range" << std::endl;
        }
    }

    return 0;
}
実行例
$ g++ -std=gnu++11 test.cpp && ./a.out 1 a 2147483647 2147483648
[1] : 1
[2] : invalid argument
[3] : 2147483647
[4] : out of range

その他の型に変換する

その他、long, float, double 向けなどに、std::stol, std::stof, std::stod が用意されています。

参考

stoi - cpprefjp C++日本語リファレンス
std::stoi - C++入門

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14