【问题标题】:C++ stoi: none of the 2 overloads could convert all the argument typesC ++ stoi:2个重载都不能转换所有参数类型
【发布时间】:2018-07-27 13:36:56
【问题描述】:

我正在编写一个与字符串有关的练习:输入一个字符串(不管是 char[] 还是 C+11 字符串,所以我选择了后者),然后在给定字符串中找到最长(具有最多字符)的升序子字符串.我的想法是扫描整个字符串并将str[i]str[i+1] 进行比较。我用stoi把每个字符转成int,看起来是这样的

if (stoi(str[i]) < stoi(str[i+1]))

但它反而给了我错误:

error C2665: 'std::stoi': none of the 2 overloads could convert all the argument types

我该如何解决?提前致谢。

【问题讨论】:

  • 如果您阅读了整个错误消息,它应该会告诉您 std::stoi 需要 字符串,而不是单个字符。
  • "我用 stoi 将每个字符转换为 int" 只是不要,直接使用chars
  • char 是整数类型 - 你不需要转换任何东西

标签: c++ string c++11


【解决方案1】:

std::stoi 将数字的字符串表示形式转换为数字本身:stoi("42") 应该等于 42。您需要的是按原样完成的字符到字符比较,无需任何额外的转换:

std::size_t i{};
while(i < str.size() - 1 && str[i] < str[i + 1]) ++i;

【讨论】:

    【解决方案2】:

    stoi 用于将std::string 转换为整数。 std::string::operator[] 为您提供所提供索引处的字符,该字符不是std::string,因此不能与stoi 一起使用。

    因为你有一个字符,你可以直接比较它们,因为所有字符类型都是整数。所以

    if (stoi(str[i]) < stoi(str[i+1]))
    

    变成

    if (str[i] < str[i+1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多