Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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++入門

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした