简体   繁体   中英

How to convert from string to int/float in C++17 with std:from_chars

What are good examples for usage of std::from_chars (C++17)

  • to convert from sequence of characters to int
  • to convert from sequence of characters to float

?

Open-Std std::from_chars

For a simple example using the int variant:

char input[] = "foo 123 bar";

int value;
auto result = std::from_chars(input + 4, input + 6, value);  // input[4] to input[6] should be a three-digit integer
if (result.ec == std::errc::invalid_argument)
{
    std::cout << "Unsuccessful parse\n";
}
else
{
    std::cout << "Successful parse, value is " << value << '\n';
}

It's important to note that since value is not initialized by me, and on failure it will be left unmodified, it can only be used if the parsing of the string-segment was successful.

This depends on what exactly you want to do, which is important for knowing how you want to handle the return value.

If you want to handle the different possible error types differently, you would compare the ec member of the std::from_chars_result to the values std::errc::invalid_argument or std::errc::out_of_range . If you only care about success/failure, you would cast it to bool instead (according to P0067R5 , in the case of success the value of ec will be false when cast to bool ). If you care about the entire string being parsed, then you will also need to check the ptr member as well.

For example, the below function will parse the C string to a std::optional<int> , with the value being empty if an error occurs or if the entire string was not parsed (eg if you try to parse something like "123.45")

auto tryParseInt(const char* src)->std::optional<int>
{
    const char* end = std::strchr(src, 0); // find the terminating null

    int parsed;
    std::from_chars_result result = std::from_chars(src, end, parsed);

    return (!(bool)result.ec && result.ptr == end)
        ? std::optional<int>{ parsed }
        : std::nullopt;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM