【问题标题】:C++ Atoi function gives error [duplicate]C ++ Atoi函数给出错误[重复]
【发布时间】:2013-08-25 10:17:48
【问题描述】:

我有一个包含 5 个字符的字符串。我想将每个单个字符转换为 int,然后将它们相乘。这是代码:

int main()
{
    int x;
    string str = "12345";
    int a[5];
    for(int i = 0; i < 5; i++)
    {
        a[i] = atoi(str[i]);
    }
    x = a[0]*a[1]*a[2]*a[3]*a[4];
    cout<<x<<endl;
}

它为带有 atoi 的行给出了这个错误:

从 'char' 到 'const char*' 的无效转换 [-fpermissive]|

我该如何解决这个问题?谢谢。

【问题讨论】:

  • atoi 适用于字符串,而不是字符。只需为此使用-'0'。也许有边界检查。

标签: c++ atoi


【解决方案1】:

你可以使用:

a[i] = str[i] - '0';

按 ASCII 字符位置进行字符到数字的转换。

【讨论】:

  • 次要的,这不是严格意义上的 ASCII,C++ 不保证 ASCII 字符集,但它确实保证这有效。
  • 如果不是 ASCII 那会是什么?而且不要说它是 Unicode……或者是吗?穆哈哈 ;)
  • @JoeDF 可能是EBCDIC,其中'J'-'I' 不是 1(并且'Z'-'A'+1 不是26)。但始终保证 IIRC '1'-'0' == 1(最高为 '9'-'0' == 9)(对于“数字字符”)。
  • 以 C++ 中的 EBCDIC 为例,请看IBM's TPF,它仍然被大量使用(例如 Sabre 和 Visa)。
  • 我以为它是为真正的旧 IBM Monsters 和 Punchcards 设计的?
【解决方案2】:

执行此操作的正确方法是std::accumulate,而不是自己滚动:

std::accumulate(std::begin(str), std::end(str), 1, [](int total, char c) {
    return total * (c - '0'); //could also decide what to do with non-digits
});

这是一个live sample,供您观赏。值得注意的是,标准保证数字字符始终是连续的,因此从'0''9' 中的任何一个中减去'0' 总是会得到数值。

【讨论】:

    【解决方案3】:

    std::atoi 采用 const char*(以空字符结尾的字符序列)

    尝试改变

     a[i]= str[i]-'0';
    

    您提供的是单个 char,因此编译器会抱怨

    【讨论】:

      【解决方案4】:

      str[i]char 不是 char *

      使用以下:-

      int x;
      std::string str = "12345";
      int a[5];
      for(int i = 0; i < 5; i++)
      {
          a[i] = str[i] -'0' ; // simply subtract 48 from char
      }
      x = a[0]*a[1]*a[2]*a[3]*a[4];
      std::cout<<x<<std::endl;
      

      【讨论】:

        【解决方案5】:

        这样看

        string str = "12345";
        int value = atoistr.c_str());
        // then do calculation an value in a loop
        int temp=1;    
        while(value){
            temp *= (value%10);
            value/=10;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-31
          相关资源
          最近更新 更多