This is my code to convert from binnary to octal ......what is the logic error in my code?

void main()
{
	double base=2;
	char bin[10000];
	int res,sum=0;
	cout<<"Enter the binnary number:";
	cin>>bin;
	int len;
	len=strlen(bin);
	int coun=0;
	for(int i=0;i<len;i=i+3)
	{
		for(int j=0;j<3;j++)
		{
			res=bin[i]-'0';
			sum=sum+res*(int) pow(base,j);	
		}	
	cout<<sum;
	}
}

sum should be set to 0 at the beginning of every iteration of the outer loop

and i is only incremented at every block of three, so "bin" is the same all three times

i make it before but it doesn't work
input :100101
output:77
the true output must be :45
what should I do

btw, binary is spelt with 1 'n' :)
heres my code:

#include<iostream>
using namespace std;

template<class t> inline
char *toBase(t val, int base, char *values) {
	register char d = 1;
	t c;
	register bool _signed = val < 0;
	if(val >= 0) for (c = base; c <= val; c *= base, d++);
	else for (c = -base; c>=val; c*=base, d++);
	register char i = d + _signed;
	char *bin = new char[i+1];
	if (_signed)
		bin[0]='-';
	for (val *= base; i - _signed;i--)
		bin[i-1] = values[
			(val /= base,(char) ((val % base) < 0 
			? -(val%base) : (val%base)))
		];
	bin[d + _signed]='\0';
	return bin;
}


// Returns index of first matched char
inline char GetIndex(char *str, char c) {
	for (char i = 0;str[i];i++) {
		if (str[i]==c)
			return i;
	}
	return 0;
}


template<class t> inline
t fromBase(char *val, char base, char *values) {
	t v = 0;
	for (char i=0;val[i];i++) {
		v *= base;
		v += GetIndex(values, val[i]);
	}
	return v;
}

int main() {
	char *bin = "100101";
	cout << (toBase(fromBase<int>(bin, 2, "01"), 8, "012345678")); // output 45
	cin.ignore();
	return 0;
}

In your code there is no need to allocate 10000 chars.

And to let the user enter the binary you dont need more than 50 chars.

int main() {
	cout<<"Enter the binnary number: ";
	char bin[50];
	cin >> bin;
	cout << (toBase(fromBase<int>(bin, 2, "01"), 8, "012345678"));
	cin.ignore();
	cin.ignore();
	return 0;
}
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.