用于字符串数字和数字值的转化,包含进制转换

主要由from_chars和to_chars两个函数组及其结果类组成。

Functions

from_chars

On success, returns a value of type std::from_chars_result such that ptr points at the first character not matching the pattern, or has the value equal to last if all characters match and ec is value-initialized.

当转换成功时,返回的结果包含一个指向转换结束的末尾字符指针和一个默认构造的std::errc对象(value-initialized

    //from_chars
    for(const std::string_view str:{"1234", "15 foo", "bar", " 42", "5000000000","3.14"}){
        std::cout<<"string:"<<std::quoted(str)<<'\n';
        int result{};
        auto [ptr,ec]=std::from_chars(str.data(),str.data()+str.size(),result,10);
        if (ec==std::errc()){
            std::cout<<"result:"<<result<<",ptr="<<std::quoted(ptr)<<'\n';
        }else if (ec == std::errc::invalid_argument)
            std::cout << "This is not a number.\n";
        else if (ec == std::errc::result_out_of_range)
            std::cout << "This number is larger than an int.\n";
    }
string:"1234"
result:1234,ptr=""
string:"15 foo"
result:15,ptr=" foo"
string:"bar"
This is not a number.
string:" 42"
This is not a number.
string:"5000000000"
This number is larger than an int.
string:"3.14"
result:3,ptr=".14"

to_chars

    //to_chars
    auto show_to_chars=[](auto... format_args){
    std::array<char,10> str;
        if (auto [ptr,ec]=std::to_chars(str.data(),str.data()+str.size(),format_args...);ec==std::errc()) {
            std::cout << std::string_view(str.data(), ptr) << '\n';
        }else{
            std::cout << std::make_error_code(ec).message() << '\n';
        }
    };
    show_to_chars(42,2);
    show_to_chars(+3.14159F);
    show_to_chars(-3.14159, std::chars_format::fixed);
    show_to_chars(-3.14159, std::chars_format::scientific, 3);
    show_to_chars(3.1415926535, std::chars_format::fixed, 10);
string:"3.14"
result:3,ptr=".14"
101010
3.14159
-3.14159
-3.142e+00
Unknown error

Classes

chars_format

(C++17)

specifies formatting for std::to_chars and std::from_chars
(enum)

from_chars_result

(C++17)

the return type of std::from_chars
(class)

to_chars_result

(C++17)

the return type of std::to_chars
(class)