【问题标题】:C++ easy way to convert int to string with unknown baseC++ 将 int 转换为具有未知基数的字符串的简单方法
【发布时间】:2013-12-06 15:25:49
【问题描述】:

这是Java代码:

int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);

现在我希望在 C++ 中也一样,但我发现的所有转换都只转换为 base 10。我 ofc 不想通过 mysleft 来实现这个,为什么要写一些已经存在的东西

【问题讨论】:

  • 我倒过来了。对不起。
  • itoa() in <cstdlib> 将允许您指定基数(2 - 36 之间)..
  • 不想自己实现这个。我记得这是开始编程课程时的常见任务,所以任何真正的程序员都不应该认为这是一种负担。
  • 自己实现。它相对简单,因此您应该知道如何执行此操作。如果你有工作面试怎么办?在那之后,你可以使用更好的东西,但你应该能够重新发明一个简单的轮子,即使你以后会买一个设计更好的轮子。
  • @Nim,itoa 不是标准的 C++。它似乎也不是标准的 C。

标签: c++ string int type-conversion


【解决方案1】:

虽然std::strtol 更灵活,但在受控情况下,您也可以使用itoa

int a = 456;
int b = 5;
char buffer[32];
itoa(a, buffer, b);

【讨论】:

【解决方案2】:

如果您想要以 8 或 16 为基数,您可以轻松使用字符串操纵器 std::octstd::hex。如果您想要任意基数,我建议您查看this question

【讨论】:

    【解决方案3】:

    没有错误处理http://ideone.com/nCj2XG:

    char *toString(unsigned int value, unsigned int radix)
    {
        char digit[] = "0123456789ABCDEFGHIJKLMNOPRSTUVWXYZ";
        char stack[32];
        static char out[33];
    
        int quot, rem;
        int digits = 0;
    
        do
        {
            quot = value / radix;
            rem = value % radix;
    
            stack[digits] = digit[rem];
            value = quot;
            digits++;
        }
        while( value );
    
        int i = 0;
        while(digits--)
        {
            out[i++] = stack[digits];
        }
    
        out[i] = 0;
    
        return out;
    }
    

    【讨论】:

      【解决方案4】:

      没有标准函数itoa,它执行到任意微积分系统的转换。但是例如,在我的编译器版本中没有实现。我的解决方案:

      #include <string>
      
      // maximum radix - base36
      std::string int2string(unsigned int value, unsigned int radix) {
          const char base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
          std::string result;
          while (value > 0) {
              unsigned int remainder = value % radix;
              value /= radix;
              result.insert(result.begin(), base36[remainder]);
          }
          return result;
      }
      

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
      • 感谢您的反馈。对答案进行了更改。
      猜你喜欢
      • 2013-09-16
      • 2017-06-09
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 2014-12-22
      • 2012-10-20
      • 2010-12-21
      • 2018-03-02
      相关资源
      最近更新 更多