24

に変換する安全な標準的な方法はありますか?std::string_viewint


C++11では次のように変換std::stringできます:stoiint

  std::string str = "12345";
  int i1 = stoi(str);              // Works, have i1 = 12345
  int i2 = stoi(str.substr(1,2));  // Works, have i2 = 23

  try {
    int i3 = stoi(std::string("abc"));
  } 
  catch(const std::exception& e) {
    std::cout << e.what() << std::endl;  // Correctly throws 'invalid stoi argument'
  }

ただしstoi、サポートしていませんstd::string_view。別の方法として、 を使用することもできますatoiが、次のように非常に注意する必要があります。

  std::string_view sv = "12345";
  int i1 = atoi(sv.data());              // Works, have i1 = 12345
  int i2 = atoi(sv.substr(1,2).data());  // Works, but wrong, have i2 = 2345, not 23

atoinullターミネータに基づいているため'\0'(たとえば、sv.substr単純に挿入/追加できないため)、どちらも機能しません。

現在、C++17 以降には もありますがfrom_chars、不十分な入力を提供するとスローされないようです:

  try {
    int i3;
    std::string_view sv = "abc";
    std::from_chars(sv.data(), sv.data() + sv.size(), i3);
  }
  catch (const std::exception& e) {
    std::cout << e.what() << std::endl;  // Does not get called
  }
4

3 に答える 3

2

@Ronと@Holtの優れた回答に基づいて、オプションの(入力が解析に失敗したstd::from_chars()場合)を返す小さなラッパーを次に示します。std::nullopt

#include <charconv>
#include <optional>
#include <string_view>

std::optional<int> to_int(const std::string_view & input)
{
    int out;
    const std::from_chars_result result = std::from_chars(input.data(), input.data() + input.size(), out);
    if(result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
    {
        return std::nullopt;
    }
    return out;
}
于 2021-01-11T22:04:37.183 に答える