C++ converts characters/strings to numeric types/integers/floats

convert string to int

std::stoi function:

Format: std:stoi(str, pos, base);

Defined in the header file string
str: the string to be processed
pos: the start position to be processed (if no parameter is entered, the default starts from the first digit)
base: base number (if no parameter is entered, the default is decimal)

Example:

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';
}

output:

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

Convert a string to a float:

std::stof function:

Format std::stof(str, pos);

Defined in the header file string
str: the string to be processed
pos: the start position to be processed (if no parameter is entered, it will start from the first position by default)

Convert characters to numbers:

std::from_chars function (C++17):

Format std::stof(first, last, value, base);

Defined in the header file charconv
first, last: the legal range of characters to be analyzed (const char*)
value: the object storing the output parameters
base: base number (default is decimal)

Example:

#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;
}

output:

42

Guess you like

Origin blog.csdn.net/Dec1steee/article/details/127138532