Namespaces
Variants

std:: atoi, std:: atol, std:: atoll

From cppreference.net
ヘッダーで定義 <cstdlib>
int atoi ( const char * str ) ;
(1)
long atol ( const char * str ) ;
(2)
long long atoll ( const char * str ) ;
(3) (C++11以降)

str が指すバイト文字列内の整数値を解釈します。暗黙の基数は常に10です。

空白文字が最初の非空白文字が見つかるまで破棄され、その後、有効な整数数値表現を形成するために可能な限り多くの文字を取り、それらを整数値に変換します。有効な整数値は以下の部分で構成されます:

  • (optional) プラスまたはマイナス記号
  • 数値の桁

結果の値を表現できない場合、すなわち変換された値が対応する戻り値の型の範囲外となる場合、動作は未定義です。

目次

パラメータ

str - 解釈されるヌル終了バイト文字列へのポインタ

戻り値

成功時の str の内容に対応する整数値。

変換が実行できない場合、 0 が返されます。

実装例

template<typename T>
T atoi_impl(const char* str)
{
    while (std::isspace(static_cast<unsigned char>(*str)))
        ++str;
    bool negative = false;
    if (*str == '+')
        ++str;
    else if (*str == '-')
    {
        ++str;
        negative = true;
    }
    T result = 0;
    for (; std::isdigit(static_cast<unsigned char>(*str)); ++str)
    {
        int digit = *str - '0';
        result *= 10;
        result -= digit; // 負数で計算してINT_MIN、LONG_MINなどをサポート
    }
    return negative ? result : -result;
}
int atoi(const char* str)
{
    return atoi_impl<int>(str);
}
long atol(const char* str)
{
    return atoi_impl<long>(str);
}
long long atoll(const char* str)
{
    return atoi_impl<long long>(str);
}

実際のC++ライブラリ実装は、Cライブラリの実装である atoi atoil 、および atoll にフォールバックします。これらは直接実装されるか( MUSL libc のように)、あるいは strtol / strtoll に委譲されます( GNU libc のように)。

#include <cstdlib>
#include <iostream>
int main()
{
    const auto data =
    {
        "42",
        "0x2A", // "0"とジャンク"x2A"として扱われ、16進数としては扱われない
        "3.14159",
        "31337 with words",
        "words and 2",
        "-012345",
        "10000000000" // 注: int32_tの範囲外
    };
    for (const char* s : data)
    {
        const int i{std::atoi(s)};
        std::cout << "std::atoi('" << s << "') is " << i << '\n';
        if (const long long ll{std::atoll(s)}; i != ll)
            std::cout << "std::atoll('" << s << "') is " << ll << '\n';
    }
}

出力例:

std::atoi('42') is 42
std::atoi('0x2A') is 0
std::atoi('3.14159') is 3
std::atoi('31337 with words') is 31337
std::atoi('words and 2') is 0
std::atoi('-012345') is -12345
std::atoi('10000000000') is 1410065408
std::atoll('10000000000') is 10000000000

関連項目

(C++11) (C++11) (C++11)
文字列を符号付き整数に変換する
(関数)
(C++11) (C++11)
文字列を符号なし整数に変換する
(関数)
バイト文字列を整数値に変換する
(関数)
バイト文字列を符号なし整数値に変換する
(関数)
(C++11) (C++11)
バイト文字列を std::intmax_t または std::uintmax_t に変換する
(関数)
(C++17)
文字シーケンスを整数または浮動小数点値に変換する
(関数)
Cドキュメント for atoi , atol , atoll