no, but Google is a good place to find out how to do it. :D
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>any builtin function in c++ that converts a decimal number into binary number??
Maybe, depending on what you want to do with it. If all you want is a string, then the bitset<> class is ideal:
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
int dec;
std::cout<<"Enter a whole number: ";
if ( std::cin>> dec )
std::cout<< std::bitset<sizeof dec * CHAR_BIT> ( dec ) <<'\n';
}
If you want an actual arithmetic value rather than a string, it's only marginally more difficult:
#include <iostream>
#include <bitset>
#include <sstream>
#include <climits>
int main()
{
int dec;
std::cout<<"Enter a whole number: ";
if ( std::cin>> dec ) {
std::istringstream iss ( std::bitset<sizeof dec * CHAR_BIT> ( dec ).to_string() );
unsigned long bit_num;
iss>> bit_num;
std::cout<< bit_num <<'\n';
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>how does this 'if statement' work?
It's just a combination of these two statements:
std::cin>> dec;
if ( cin )
Put simply, if ( cin ) says "Is the stream happy?". Since dec is an integer, if you typed a letter instead of a number, std::cin>>dec would fail with a conversion error, placing the stream in a failure state. Because the stream is in a failure state, if ( cin ) isn't true, so the body of the statement isn't executed. But if you type a valid integer, std::cin>>dec succeeds and doesn't set any failure flags, so if ( cin ) is true and the body of the statement is executed.
C++ has all kinds of shortcuts. One of them is being able to combine those two statements into one:
if ( std::cin>> dec )
:)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401