How can I convert a std::string to int?

后端 未结 19 1027
梦毁少年i
梦毁少年i 2020-11-22 02:10

Just have a quick question. I\'ve looked around the internet quite a bit and I\'ve found a few solutions but none of them have worked yet. Looking at converting a string to

19条回答
  •  醉话见心
    2020-11-22 02:53

    To be more exhaustive (and as it has been requested in comments), I add the solution given by C++17 using std::from_chars.

    std::string str = "10";
    int number;
    std::from_chars(str.data(), str.data()+str.size(), result);
    

    If you want to check whether the conversion was successful:

    std::string str = "10";
    int number;
    auto [ptr, ec] = std::from_chars(str.data(), str.data()+str.size(), result);
    assert(ec == std::errc{});
    // ptr points to chars after read number
    

    Moreover, to compare the performance of all these solutions, see the following quick-bench link: https://quick-bench.com/q/GBzK53Gc-YSWpEA9XskSZLU963Y

    (std::from_chars is the fastest and std::istringstream is the slowest)

提交回复
热议问题