std::atoi、std::atol、std::atoll
From cppreference.com
| ヘッダ <cstdlib> で定義 |
||
| int atoi( const char* str ); |
(1) | |
| long atol( const char* str ); |
(2) | |
| long long atoll( const char* str ); |
(3) | (C++11以降) |
strが指すバイト文字列から整数値を解釈します。暗黙の基数は常に10です。
先頭の空白文字をすべて無視し、最初の非空白文字が見つかったら、有効な整数表現を形成できるだけ多くの文字を取り込み、それらを整数値に変換します。有効な整数値は、以下の部分で構成されます。
- (任意)プラスまたはマイナスの記号
- 数字
結果の値が表現できない場合、つまり変換された値が対応する戻り値の型の範囲外である場合、動作は未定義です。
目次 |
[編集] パラメータ
| 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; // calculate in negatives to support 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", // treated as "0" and junk "x2A", not as hexadecimal "3.14159", "31337 with words", "words and 2", "-012345", "10000000000" // note: out of int32_t range }; 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) |
文字列を符号付き整数に変換する (function) |
| (C++11)(C++11) |
文字列を符号なし整数に変換する (function) |
| (C++11) |
バイト文字列を整数値に変換する (関数) |
| (C++11) |
バイト文字列を符号なし整数値に変換する (関数) |
| (C++11)(C++11) |
バイト文字列を std::intmax_t または std::uintmax_t に変換する (関数) |
| (C++17) |
文字シーケンスを整数値または浮動小数点数値に変換する (関数) |
| C言語のドキュメント (atoi、atol、atoll)
| |