Decimal to binary conversion

I've recently started with c++ and wrote a program to convert decimal number into binary number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream.h>
#include<conio.h>
temp==bin;
void main()
{
	int dec,bin,temp;
	cout<<" decimal number"<<endl;
	cin>>dec;       
	while(dec!=0)
	{
	bin=dec%2;
	dec=dec/2;
	cout<<bin; //program works here but the numbers are reversed.
        temp=bin%10;//so this is my (failed) attempt to store and reverse the digits.
	cout<<temp;
	temp=temp/10;


        }
        getch();

}


Is it possible to complete the program without using namespace?
Thanks in advance.
Last edited on
I've recently started with c++

iostream.h is old and conio.h is non-standard.
include <iostream> instead of <iostream.h>
(note: you might have to write std::cin and std::cout instead of cin and cout when making this change)

instead of getch(), which is in conio.h and non-standard, you could use this function to be standard-conform:
1
2
3
4
5
6
7
8
#include <iostream>
#include <string>
void wait_for_enter() 
{
    std::string temp;
    std::cout << "Press enter to continue...";
    std::getline(std::cin, temp);
}



Is it possible to complete the program without using namespace?

The answer is yes but i don't really understand the question.
Last edited on
You must be careful to separate the printout or string input of a number with the number as it is stored in the actual computer. All numbers are stored as 1's and 0's.
1011 will be treated as the decimal number one thousand and eleven not as its binary interpretation of eleven.
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
#include <iostream>

using namespace std;

int main()
{
	int dec;
	string bin;
	int temp;

	cout << " decimal number: ";
	cin  >> dec;

	while(dec != 0)
	{
	    if (dec % 2 == 1)
            bin = "1" + bin;
        else
            bin = "0" + bin;

            dec = dec / 2;
	}
    cout << endl << bin << endl;
    return 0;
}

Last edited on
Topic archived. No new replies allowed.