can someone look at this? in theory it should work but i cant figure it out
thanks in advance

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
void binToDec(string getBinary);
int main()
{
	string getBinary;
	cout<<"Enter a Binary Number:"<<endl;
	cin>>getBinary;
	binToDec(getBinary);
	
return 0;
}
void binToDec(string getBinary)
{
	int setLength,total=0;
	double placeholder=0;
	setLength=getBinary.size();
	
	for(int i=setLength;i>0;i--)
	{
		int num=pow(2.0,placeholder);
		int test=getBinary[i];
		if (test==1)
		{
			total=total+num;
		}

		placeholder=placeholder +1;
	
	}
	cout<<total<<endl;


}

I guess using string is not the good idea.
What we use to do was.... some how take the binary in the int or long.

then take a loop and extract the element one by one form the last...

I guess this is the efficient method.. some how you are wasting too much memory space using string.

int dec;
int bin;
cin>>bin;

for(int i=0; bin!=0; bin/=10)
  dec+=bin%10*pow(2, i++);

oh sorry i forgot to add i have to use string as binary this is hw for school. pow only works with double. :(

oh sorry i forgot to add i have to use string as binary this is hw for school. pow only works with double. :(

if you are such crazy about the string.
then you must subtract 48 from the each character of the string

as ASCII value of 1 is 49
when you subtract 49-48 = 1
then you can use it as normally

What

can someone look at this? in theory it should work but i cant figure it out
thanks in advance

if (test==1)

That line should be if (test == '1') 1 is different to '1' (character code 49, as Rhohitman said). Also, for powers of 2 you don't have to use pow(). Using the shift operator<< works fine for integers. So pow(2., x) can be replaced with 1<<x

Thanks alot :d

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.