Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::from_chars

      From cppreference.com
      <cpp‎ |utility
       
       
       
      Defined in header<charconv>
      std::from_chars_result

          from_chars(constchar* first,constchar* last,

                     /* integer-type */& value,int base=10);
      (1)(since C++17)
      (constexpr since C++23)
      std::from_chars_result

          from_chars(constchar* first,constchar* last,
                     /* floating-point-type */& value,

                     std::chars_format fmt= std::chars_format::general);
      (2)(since C++17)

      Analyzes the character sequence[firstlast) for a pattern described below. If no characters match the pattern or if the value obtained by parsing the matched characters is not representable in the type ofvalue,value is unmodified, otherwise the characters matching the pattern are interpreted as a text representation of an arithmetic value, which is stored invalue.

      1) Integer parsers: Expects the pattern identical to the one used bystd::strtol in the default ("C") locale and the given non-zero numeric base, except that
      • "0x" or"0X" prefixes are not recognized ifbase is 16
      • only the minus sign is recognized (not the plus sign), and only for signed integer types ofvalue
      • leading whitespace is not ignored.
      The library provides overloads for all cv-unqualified(since C++23) signed and unsigned integer types andchar as the referenced type of the parametervalue.
      2) Floating-point parsers: Expects the pattern identical to the one used bystd::strtod in the default ("C") locale, except that
      In any case, the resulting value is one of at most two floating-point values closest to the value of the string matching the pattern, after rounding according tostd::round_to_nearest.
      The library provides overloads for all cv-unqualifiedstandard(until C++23) floating-point types as the referenced type of the parametervalue.

      Contents

      [edit]Parameters

      first, last - valid character range to parse
      value - the out-parameter where the parsed value is stored if successful
      base - integer base to use: a value between 2 and 36 (inclusive).
      fmt - floating-point formatting to use, a bitmask of typestd::chars_format

      [edit]Return value

      On success, returns a value of typestd::from_chars_result such thatptr points at the first character not matching the pattern, or has the value equal tolast if all characters match andec is value-initialized.

      If there is no pattern match, returns a value of typestd::from_chars_result such thatptr equalsfirst andec equalsstd::errc::invalid_argument.value is unmodified.

      If the pattern was matched, but the parsed value is not in the range representable by the type ofvalue, returns value of typestd::from_chars_result such thatec equalsstd::errc::result_out_of_range andptr points at the first character not matching the pattern.value is unmodified.

      [edit]Exceptions

      Throws nothing.

      [edit]Notes

      Unlike other parsing functions in C++ and C libraries,std::from_chars is locale-independent, non-allocating, and non-throwing. Only a small subset of parsing policies used by other libraries (such asstd::sscanf) is provided. This is intended to allow the fastest possible implementation that is useful in common high-throughput contexts such as text-based interchange (JSON orXML).

      The guarantee thatstd::from_chars can recover every floating-point value formatted bystd::to_chars exactly is only provided if both functions are from the same implementation.

      A pattern consisting of a sign with no digits following it is treated as pattern that did not match anything.

      Feature-test macroValueStdFeature
      __cpp_lib_to_chars201611L(C++17)Elementary string conversions (std::from_chars,std::to_chars)
      202306L(C++26)Testing for success or failure of<charconv> functions
      __cpp_lib_constexpr_charconv202207L(C++23)Addconstexpr modifiers tostd::from_chars andstd::to_chars overloads for integral types

      [edit]Example

      Run this code
      #include <cassert>#include <charconv>#include <iomanip>#include <iostream>#include <optional>#include <string_view>#include <system_error> int main(){for(std::string_viewconst str:{"1234","15 foo","bar"," 42","5000000000"}){std::cout<<"String: "<<std::quoted(str)<<". ";int result{};auto[ptr, ec]= std::from_chars(str.data(), str.data()+ str.size(), result); if(ec==std::errc())std::cout<<"Result: "<< result<<", ptr -> "<<std::quoted(ptr)<<'\n';elseif(ec==std::errc::invalid_argument)std::cout<<"This is not a number.\n";elseif(ec==std::errc::result_out_of_range)std::cout<<"This number is larger than an int.\n";} // C++23's constexpr from_char demo / C++26's operator bool() demo:auto to_int=[](std::string_view s)->std::optional<int>{int value{};#if __cpp_lib_to_chars >= 202306Lif(std::from_chars(s.data(), s.data()+ s.size(), value))#elseif(std::from_chars(s.data(), s.data()+ s.size(), value).ec==std::errc{})#endifreturn value;elsereturnstd::nullopt;}; assert(to_int("42")==42);assert(to_int("foo")==std::nullopt);#if __cpp_lib_constexpr_charconv and __cpp_lib_optional >= 202106    static_assert(to_int("42")==42);    static_assert(to_int("foo")==std::nullopt);#endif}

      Output:

      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.

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 2955C++17this function was in<utility> and usedstd::error_codemoved to<charconv> and usesstd::errc
      LWG 3373C++17std::from_chars_result might have additional membersadditional members are prohibited

      [edit]See also

      the return type ofstd::from_chars
      (class)[edit]
      (C++17)
      converts an integer or floating-point value to a character sequence
      (function)[edit]
      (C++11)(C++11)(C++11)
      converts a string to a signed integer
      (function)[edit]
      (C++11)(C++11)(C++11)
      converts a string to a floating point value
      (function)[edit]
      converts a byte string to an integer value
      (function)[edit]
      converts a byte string to a floating-point value
      (function)[edit]
      reads formatted input fromstdin, a file stream or a buffer
      (function)[edit]
      extracts formatted data
      (public member function ofstd::basic_istream<CharT,Traits>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/from_chars&oldid=179101"

      [8]ページ先頭

      ©2009-2025 Movatter.jp