Help with a decimal to binary issue.

Ok, this is an assignment question. I am not asking for someone to do my work. I have only been learning c++ for 7 weeks now.


So i have this code to work out the demical to binary but the code is backwards. Now i know I have to make it into a string but i am unsure on how to do that.

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
27
28
29
#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <string>
#include <conio.h>


using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

int num,rem;

cout << "\nEnter Positive Number : ";
cin >> num;

        do
        {
            rem = num%2;
            num = num/2;
            cout << rem;
                  
        } while (num>0);

_getche();
return 0;

}
You can convert the remainder (which is an integer) into a character something like this:
 
char digit = rem + '0';

Then you could either concatenate that char on to the front of a std::string, or store each digit in consecutive locations of a character array, to give a null-terminated c-string.

The std::string approach is much easier to code, though the other approach may be more efficient.
sorry could you give me a little bit more information
Sure, but since you said it was an assignment, I didn't think it was appropriate to do all the work for you. So, which part specifically do you need help with?
Yes I know,

Just a little bit more information for writing into a string.

We are just briefly covering some of the different areas and unsure of writing it.
Well, here I'm reiterating my first answer:
1
2
3
4
5
6
7
8
9
10
11
    std::string result;

    do
    {
        rem = num%2;
        num = num/2;
        char digit = rem + '0';
        // here concatenate digit with result        
    } while (num>0);

    cout << result;


That shows the structure of the code. All you have to do is line 8.

You could use the + operator (very easy) or the insert() function.
http://www.cplusplus.com/reference/string/string/operator+/
http://www.cplusplus.com/reference/string/string/insert/
Last edited on
Topic archived. No new replies allowed.