my code convert from decimal to octal
here is but say input 26 ,output 23 i want output =32
what can i do?

void main()
{
	
	int value;
	cin>>value;   //value=26
	int rem=0;
	while(value!=0)
	{
	 rem=value%8;
		if(rem%8!=0)
		{
			value--;
		}
		i++;
		value=value/8;
		
		cout<<rem;  //output  23

Recommended Answers

All 3 Replies

you are not explaining your problem clearly...from what you said you want to convert a number input from decimal to octal. from your code, you are finding the remainder then you output it and then you are calculating value...is this the whole code or part of it???why dont you elaborate on the question and your problem a little more

Look my code here isn't complete.As output must be 32 if input is 26
The output in my code 23
I just wnt to inverse it
Do you understand me?

When you make a conversion like that, you get the digits in reverse. There are a number of ways to swap the order. First you have recursion:

#include <iostream>
#include <ostream>

void to_octal ( std::ostream& out, int value, int n = 0 )
{
  if ( value == 0 ) {
    if ( n == 0 )
      out<< value;

    return;
  }

  to_octal ( out, value / 8, n + 1 );
  out<< value % 8;
}

int main()
{
  to_octal ( std::cout, 26 );
  std::cout<<'\n';
}

Another is converting each digit to a character and storing them in a string. You can either push them to the front of the string if that's a supported operation, or reverse the string at the end:

#include <iostream>
#include <string>

std::string to_octal ( int value )
{
  if ( value == 0 )
    return "0";

  std::string result;

  while ( value != 0 ) {
    char digit = value % 8 + '0';

    result = digit + result;
    value /= 8;
  }

  return result;
}

int main()
{
  std::cout<< to_octal ( 26 ) <<'\n';
}
#include <algorithm>
#include <iostream>
#include <string>

std::string to_octal ( int value )
{
  if ( value == 0 )
    return "0";

  std::string result;

  while ( value != 0 ) {
    char digit = value % 8 + '0';

    result += digit;
    value /= 8;
  }

  std::reverse ( result.begin(), result.end() );

  return result;
}

int main()
{
  std::cout<< to_octal ( 26 ) <<'\n';
}

Or if you don't want to do a character conversion for some reason, you can store the digits on a stack. When they get popped off, everything will be in the right order:

#include <iostream>
#include <ostream>
#include <stack>

void to_octal ( std::ostream& out, int value )
{
  if ( value == 0 )
    out<< value;
  else {
    std::stack<int> save;

    while ( value != 0 ) {
      save.push ( value % 8 );
      value /= 8;
    }

    while ( !save.empty() ) {
      out<< save.top();
      save.pop();
    }
  }
}

int main()
{
  to_octal ( std::cout, 26 );
  std::cout<<'\n';
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.