I need to create a base conversion program. It needs to accept any input and base and output the number converted to the other base form. For example, I input 4 with a base of 2 and I should get 100 as an output. Also, when it was working (before I added in the loop) I would get 0 regardless of what I entered. I guess it is giving me only the one placement value. How do I get the output to be the entire string of values? I have now added the prepend string function to the code. However, it is still not working. Regardless of what I enter, I get a smiley face. What does that mean and how do I fix it. Thank you in advance.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
string prependStr(string, int);
int main() {
int num, base;
int remainder;
string result = "";
cout << "Please enter a positive integer: ";
cin >> num;
cout << "Please enter a base: ";
cin >> base;
while (num != 0) {
remainder = num % base;
num = num / base;
cout << result;
}
system("pause");
return 0;
}
string prependStr(string result, int digit) {
return result.insert(0, to_string(digit));
}
First, there's a bug in the way you've specified the loop while (num > 0); {...
is equivalent to
1 2 3
while (num > 0) // while num>0
; // do nothing
{... // Then do this code once.
So what you want to do is:
- prompt for the number
- prompt for the base
- compute the number in the new base.
- print it out.
Here is your code with the loops fixed. I've also added a line to print each digit as it's found. But notice that the digits come out in reverse order from what you want: the first digit that comes out is the least significant, then the next and so on. So you will need to something to remedy this. shadowCODE gave one example. There are others.
Unfortunately, vectors are beyond the scope of the class at the moment. shadowCODE, is there a simpler way of doing this that would make sense for a first timer? I am trying the prependstr but it isn't working.
Thank you dhayden for explaining what having the ; in the loop meant. I have eliminated that portion.
The easiest way is to use a C string. Create char array to store the result. 50 characters should be more than enough. Put a null terminator at the end:
char *dst = &out[BufSize-1];
...
while (num > 0) {
remainder = (num % base);
*--dst = '0' + remainder;
num = num / base;
}
When you exit this loop, dst points to a C-string containing the converted number.
Note how I'm using dst. It starts by pointing to the null terminator. At line 5, I pre-decrement it, and then store the digit to the location it points at. The reason for doing it this way is that when you leave the loop, it points right at the string: no need for further adjustments.