C++ は文字/文字列を数値型/整数/浮動小数点数に変換します

文字列を int に変換する

std::stoi 関数:

形式: std:stoi(str, pos, Base);

ヘッダーファイルで定義 string
str: 処理対象の文字列
pos: 処理対象の開始位置 (パラメータが入力されていない場合、デフォルトは最初の桁から開始されます)
Base: ベース番号 (パラメータが入力されていない場合、デフォルトは10進数)

例:

int main()
{
    
    
    std::string str1 = "45";
    std::string str2 = "3.14159";
    std::string str3 = "31337 with words";
    std::string str4 = "words and 2";
 
    int myint1 = std::stoi(str1);
    int myint2 = std::stoi(str2);
    int myint3 = std::stoi(str3);
    // 错误: 'std::invalid_argument'
    // int myint4 = std::stoi(str4);
 
    std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
    std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
    std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
    //std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}

出力:

std::stoi("45") is 45
std::stoi("3.14159") is 3
std::stoi("31337 with words") is 31337

文字列を浮動小数点数に変換します。

std::stof 関数:

形式 std::stof(str, pos);

ヘッダーファイルで定義 string
str: 処理対象の文字列
pos: 処理対象の開始位置 (パラメータが入力されていない場合、デフォルトで最初の位置から開始されます)

文字を数字に変換します。

std::from_chars 関数 (C++17):

形式 std::stof(first、last、value、base);

ヘッダーファイルで定義 charconv
first、last: 解析対象の有効な文字範囲 (const char*)
value: 出力パラメータを格納するオブジェクト
base: 基数 (デフォルトは 10 進数)

例:

#include <iostream>
#include <charconv>
#include <array>
 
int main()
{
    
    
    std::array<char, 10> str{
    
    "42"};
    int result;
    std::from_chars( str.data(), str.data()+str.size(),result );
    std::cout << result;
    return 0;
}

出力:

42

おすすめ

転載: blog.csdn.net/Dec1steee/article/details/127138532