名前空間
変種
操作

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

提供: cppreference.com
< cpp‎ | string‎ | byte
ヘッダ <cstdlib> で定義
int       atoi( const char *str );
long      atol( const char *str );
long long atoll( const char *str );
(C++11以上)

str の指すバイト文字列内の整数値を解釈します。

最初の非ホワイトスペース文字が見つかるまで、あらゆるホワイトスペース文字を破棄し、その後、有効な整数表現を形成する可能な限り多くの文字を取得し、それを整数値に変換します。 有効な整数値は以下の部分から構成されます。

  • (オプション) 正または負の符号
  • 数字

目次

[編集] 引数

str - 解釈するヌル終端バイト文字列を指すポインタ

[編集] 戻り値

成功した場合は str の内容に対応する整数値。 変換後の値が対応する戻り値の型の範囲外の場合、戻り値は未定義です。 変換が行えない場合は、 0 が返されます。

[編集]

#include <iostream>
#include <cstdlib>
 
int main()
{
    const char *str1 = "42";
    const char *str2 = "3.14159";
    const char *str3 = "31337 with words";
    const char *str4 = "words and 2";
 
    int num1 = std::atoi(str1);
    int num2 = std::atoi(str2);
    int num3 = std::atoi(str3);
    int num4 = std::atoi(str4);
 
    std::cout << "std::atoi(\"" << str1 << "\") is " << num1 << '\n';
    std::cout << "std::atoi(\"" << str2 << "\") is " << num2 << '\n';
    std::cout << "std::atoi(\"" << str3 << "\") is " << num3 << '\n';
    std::cout << "std::atoi(\"" << str4 << "\") is " << num4 << '\n';
}

出力:

std::atoi("42") is 42
std::atoi("3.14159") is 3
std::atoi("31337 with words") is 31337
std::atoi("words and 2") is 0

[編集] 関連項目

(C++11)(C++11)(C++11)
文字列を符号付き整数に変換します
(関数) [edit]
(C++11)(C++11)
文字列を符号なし整数に変換します
(関数) [edit]
バイト文字列を整数値に変換します
(関数) [edit]
バイト文字列を符号なし整数値に変換します
(関数) [edit]
(C++11)(C++11)
バイト文字列を std::intmax_t または std::uintmax_t に変換します
(関数) [edit]
文字シーケンスを整数値または浮動小数点値に変換します
(関数) [edit]
atoi, atol, atollC言語リファレンス