convert binary to decimal c++ stl

To convert a binary number to decimal in C++ using the STL library, you can follow these steps:

  1. Include the necessary headers: Begin by including the necessary headers for input/output and the STL library:
#include <iostream>
#include <bitset>
  1. Read the binary number: Prompt the user to enter the binary number, and store it in a string variable:
std::string binary;
std::cout << "Enter a binary number: ";
std::cin >> binary;
  1. Convert the binary number: Use the std::bitset class from the STL library to convert the binary number to its decimal representation:
std::bitset<32> decimal(binary);

The std::bitset class provides a convenient way to manipulate binary representations as if they were integers.

  1. Output the decimal representation: Finally, output the decimal representation of the binary number using the std::cout object:
std::cout << "Decimal: " << decimal.to_ulong() << std::endl;

The to_ulong() function of the std::bitset class converts the binary representation to an unsigned long integer.

Here's the complete code:

#include <iostream>
#include <bitset>

int main() {
    std::string binary;
    std::cout << "Enter a binary number: ";
    std::cin >> binary;

    std::bitset<32> decimal(binary);

    std::cout << "Decimal: " << decimal.to_ulong() << std::endl;

    return 0;
}

This code will prompt the user to enter a binary number, convert it to decimal, and output the result.