How can I use dynamic memory allocation for converting decimal to octal?

时间:2016-11-26 18:31:33

标签: c++ decimal octal

I have two pieces of code that I wrote. This one doesn't work because it writes the code backwards.

void convertNum1(long a) {
    while (a!=0) {
        long remainder = 0;
        remainder = a % 8;
        a /= 8;

        cout << remainder;
    }
    cout << endl;
}

I wrote this code because the first one doesn't work. Basically my idea is to fill up an array with the elements and then count it backwards.

void convertNum2(long a) {
    long *pointer = NULL;
    int k = 1;
    long c = a;
    while (c != 0) {
        c/= 8;
        k++;
    }
    pointer = new long[k];

    int rem;
    for (int j = 0;j<k;j++) {
        rem = a / 8;
        *(pointer + j) = rem;
    }
    for (int j = k; j > 0;j--) {
        cout << *(pointer + j);
    }

    delete []pointer;
}

1 个答案:

答案 0 :(得分:0)

我建议使用stack。将八进制数字推入堆栈,然后将其弹出(它们将按照正确的顺序)。

BTW,您可以随时作弊并使用std::oct I/O manipulator

std::string Dec_To_Oct(unsigned long number)
{
  static const char octal_char_digits[] = "01234567";
  std::stack<char>  octal_number;
  while (number > 0U)
  {
    octal_digit = number % 8;
    const char d = octal_char_digits[octal_digit];
    octal_number.push(d);
    number = number / 8;
  }
  std::string octal_text;
  while (!octal_number.empty())
  {
     const char d = octal_number.top();
     octal_text += d;
     octal_number.pop();
  }
  return octal_text;
}