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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
#include <string>
void Get_binary(std::string &binary);
void Converted_binary(std::string binary, int len, int &decimal, int number);
int main()
{
std::string binary = "";
int decimal = 0, number = 1;
std::cout << "Please enter your binary number.." <<std::endl;
Get_binary(binary);
int len = binary.length()-1; // To start from the far right location of string
Converted_binary(binary, len, decimal, number);
std::cout << std::endl << "The entered binary number equals " << decimal << std::endl;
return 0;
}
void Get_binary(std::string &binary)
{
char zero_1;
bool ok;
std::cout << "Enter 'x' to end binary inputs" << std::endl;
do
{
ok = true;
binary = "";
do
{
std::cin >> zero_1;
if(zero_1 == '0' || zero_1 == '1')
binary+=zero_1;
else if (zero_1 != 'x' )// Edited.
// Did not need '&& zero_1 !='0' && zero_1 !='1';
{
std::cout << std::endl << "Please enter only binary numbers consisting of '0's and '1's" << std::endl << std::endl;
ok = false; // If not a 0, 1 or an x (to end binary input)
}
}while(zero_1 != 'x');
}while(!ok);
}
void Converted_binary(std::string binary, int len, int &decimal, int number)
{
if(binary[len] == '1')
decimal+=number;
number*=2;
len--;
if(len != -1)
Converted_binary(binary, len, decimal, number);
}
|