#include<iostream>
#include<string>
usingnamespace std;
int bin2dec(int);
int main()
{
int bin;
cout<<"Enter a binary number: ";
cin >>bin;
cout<<"The decimal equivalent of: " << bin << " is: " << bin2dec(bin) << endl;
}
int bin2dec(int x)
{
int output = 0;
for(int i=0; x > 0; i++) {
if(x % 10 == 1) {
output += (1 << i);
}
x /= 10;
}
return output;
}
When I switch the header to a string i run into the problem of having to switch
x /= 10; because it doesn't allow me to divide the string size by 10. I just need help converting the program so that it runs with a string that is all!
well you are returning an int when you should be returning a string. The output should be a string and not an int. Also, I think that your decimal-binary is a bit off.
#include <iostream>
#include <string>
// invariant: binary_string consists of '0's and '1's
// invariant: result can be held in an an unsigned int
// error checking elided for brevity
unsignedint bin2dec( const std::string& binary_string )
{
unsignedint result = 0 ;
// http://www.stroustrup.com/C++11FAQ.html#forfor( char c : binary_string ) // for each character in the binary string
{
result *= 2 ; // shift result left by one binary digit
if( c == '1' ) result += 1 ; // add one if the bit is set
}
return result ;
}