Problem with conversion of an (int) as a type to (string)

Hello, I was asked to write a program which converted binary to decimals
with the header
int bin2Dec(const str& binaryString)

but instead I created the program with the header
int bin2Dec(int)

and I'm not sure how to change everything in my code so it works correctly but it runs fine right now. This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<string>
using namespace 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.

http://www.cplusplus.com/doc/hex/
http://www.learncpp.com/cpp-tutorial/37-converting-between-binary-and-decimal/
http://www.wikihow.com/Convert-from-Decimal-to-Binary

[edit]

Just realized I misread thinking you wanted decimal to binary and not binary to decimal.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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
unsigned int bin2dec( const std::string& binary_string )
{
    unsigned int result = 0 ;

    // http://www.stroustrup.com/C++11FAQ.html#for
    for( 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 ;
}
Topic archived. No new replies allowed.