Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Lab task 2: Create a program that asks the user for a binary number (string) and

ID: 3585627 • Letter: L

Question

Lab task 2: Create a program that asks the user for a binary number (string) and outputs the equivalent base 10 (decimal form) of the inputted binary string.

Write your code in the main function. Use cin to get the input and cout to output the result. Use the string class to extract each binary digit to get a single integer to use in calculations:

#include<iostream>

#include<string>

using namespace std;

void main()

{

       string binary, b;

       int digit;   

       cout << "Enter a binary string: ";

       cin >> binary;

      

//get the most significant bit of binary

       b=binary[0];

       digit = atoi(b.c_str());

      

}

Explanation / Answer

#include<iostream>
#include<string>
#include<math.h>
using namespace std;

main()
{
string binary, b;
int dec = 0, help = 0, digit;   

cout << "Enter a binary string: ";
cin >> binary;
  
//get the most significant bit of binary

// looping through each number in binary string
for(int i=binary.length()-1;i>=0;i--, help++)
{
b=binary[i]; // taking each number
digit = atoi(b.c_str());
dec = dec + digit*pow(2,help); // calculating
}
//digit = atoi();
cout << dec;
}

/*SAMPLE OUTPUT

Enter a binary string: 1111
15

Enter a binary string: 1100
12

*/