0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】基数変換 std::stoi()の引数について

Posted at

stoi関数とは

C++11以降の環境では、文字列 str を数値として読み取って、int 型の値に変換するために、標準ライブラリstoi()を用いることができます。以下に記述例を示します。

std::string n = "10100110"
std::cout << std::stoi(n,0,2) 
#include <iostream>
#include <string>

int main() {
    std::string s = "123px";
    size_t pos; // 変換が終了した位置を格納する変数

    // 第2引数に pos のアドレス (&pos) を渡す
    int value = std::stoi(s, &pos, 10);

    std::cout << "変換された数値: " << value << std::endl;
    std::cout << "変換されなかった部分: '" << s.substr(pos) << "'" << std::endl;

    return 0;
}

第1引数: 変換したい文字列です。

第2引数: 通常は nullptr または 0 を指定して、文字列の最初から変換を始めます。この引数は、変換がどこまで行われたかを知りたい場合に、その位置を格納する変数(ポインタ)を渡すためにも使われます。第2変数で0以外の数を入れるとコンパイルエラーになります。

第3引数: 変換する文字列が何進数で表現されているかを示す基数です。

stoiの関連関数

stoi()は、以外にもC++標準ライブラリには他にも類似の関数が存在します。

stol(): long型に変換
stoll(): long long型に変換
stof: float 型に変換
stod: double型に変換

練習問題

競技プログラミングの鉄則 演習問題集より

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?