I'm a beginner to C++ and I'm trying to make a program that takes in a user-determined decimal integer number and prints its standard decimal counterpart. The mathematics behind it is quite simple and I've figured out what to do. I've already written a code in Java that does all of this and it works without error. I'm having issues in C++ however.
Given a number such as 57, it must be divided by 2 continuously. An even number will produce no remainder, which gives a 0 in binary. An odd number will give a remainder of 1, which gives a 1 in binary. This process continues until the number reaches 0. Then all of the remainders are counted from last to first to form the binary number. For 57 it would be 111001 (according to my Java program, which is correct).
Whatever number is entered will be assigned as A, be it 57 or 237, etc. R is the remainder, and that is simply found by using R = A%2. Then A is divided by 2 and the process repreats.
I just need to get all of the remainders to be put together in a string so they can be displayed. Say I have a string X that is initially "". Each time R is found, it needs to be put at the beginning of that string. Once the process of diving A by 2 is done, a nice mess of 0s and 1s should come together.
I just cant figure out how to put the remainder R into the beginning of the string. This is in a while loop so it needs to add onto string X each time. I've tried looking into insert, stringstream and a few others but the scenarios are different such that all I end up with is more errors.
(A and R are integers. String X is "".)
1 2 3 4 5 6 7 8 9
|
while (A>0) {
R = A%2;
//Something to add R to the beginning of string X
A = A/2;
if (A==0) {
cout << "Binary: " << X << endl;
break;
}
}
|
Can anyone help?