How can I improve this C++ program?

I made a simple decimal to binary converter, but it's only my second program, so I don't know much.
Instead of printing every digit separately, is it possible to add each decimal to a variable as it gets them and then just print that variable at the end? If that makes sense? Also is there a better way than having all these if statements? And is there a way to stop the user entering any more than 2 digits? Sorry if I'm not making any sense. :D

#include <iostream>
using namespace std;

int GetNumber()
{
int x;
cin >> x;
return x;
}

void Convert()
{
int x = GetNumber();
if
(x >= 128)
{
cout << 1;
x = x - 128;
}
else
cout << 0;
if
(x >= 64)
{
cout << 1;
x = x - 64;
}
else
cout << 0;
if
(x >= 32)
{
cout << 1;
x = x - 32;
}
else
cout << 0;
if
(x >= 16)
{
cout << 1;
x = x - 16;
}
else
cout << 0;
if
(x >= 8)
{
cout << 1;
x = x - 8;
}
else
cout << 0;
if
(x >= 4)
{
cout << 1;
x = x - 4;
}
else
cout << 0;
if
(x >= 2)
{
cout << 1;
x = x - 2;
}
else
cout << 0;
if
(x >= 1)
{
cout << 1 << endl;
x = x - 1;
}
else
cout << 0 << endl;
}

int main()
{
cout << "INTEGER TO BINARY CONVERTER:" << endl;
cout << "Enter a 1 or 2 digit integer..." << endl;
Convert();
system("pause");
return 0;
}

Use std::bitset if you want:
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
#include <iostream>
#include <bitset>
using namespace std;

int GetNumber()
{
unsigned int x;
cin >> x;
return x;
}

void Convert()
{
unsigned int x = GetNumber();
cout << bitset<8> (x);

}

int main()
{
cout << "INTEGER TO BINARY CONVERTER:" << endl;
cout << "Enter a 1 or 2 digit integer..." << endl;
Convert();
//system("pause");
return 0;
}
Last edited on
Now why would one post two threads? http://cplusplus.com/forum/windows/41038/
Last edited on
@ WriteGreatCode: With a submission timestamp =< 60 seconds apart I'd chalk that up to a double submission by mistake.

@ mordoran: Nice call with the bitset!
Topic archived. No new replies allowed.