1

I have a simple program that converts decimal numbers to binary numbers. No errors come up when I run the program but I do get a single question mark. I should get a set of values like "00101" I am trying to use a function that returns a string as well. Here is my code,

#include <iostream>
using namespace std;
#include <string>

string convert(int num)
{
    string binary;
    int remainder;

    while (num !=0 )
    {
        remainder = num % 2;
        num = num / 2;
        binary = remainder;
    }
    return binary;
}

int main()
{
   int number;
   string binaryNum;
   cout << "Enter a Number:";
   cin >> number;

   binaryNum = convert(number);
   cout << "This is your number in binary form:" << binaryNum << endl;

   system("pause");
}

Any ideas? Thanks for the help

CuriousCoder97
  • 37
  • 1
  • 11
  • code `return binary;` in `while` will return on first loop. why you doing that ? – Farhad Sep 11 '17 at 03:34
  • Sorry, I was trying to figure out if that is where the issue was. I have tried to remove it but I get the same problem. – CuriousCoder97 Sep 11 '17 at 03:36
  • You are trying to assign integer value into a string without converting it to a string. This is the main issue. I believe you can fix other logical errors in your code after fixing it. :) – Naseef Chowdhury Sep 11 '17 at 09:03

2 Answers2

3

There are several problems with this code. First, you are assigning the string binary using the = sign on the line binary = remainder. What you probably meant to write was binary += remainder, to append the remainder to the string.

The second problem is also on that line. Both string::operator= and string::operator+= have overloads that take a char. Those overloads are called, when you pass in an int. So the string is being set to the character whose ascii value is 0 or 1, thus the question mark character, which is not what you are looking for. You can use std::to_string to easily convert your int into a string. Or if you need any level of control over the formatting, you can use std::ostringstream as in this answer.

In other words, change binary = remainder; to binary += std::to_string(remainder).

Third problem: There is a return statement inside the while loop. The function will return after one iteration of the loop, no matter how large num is. Remove that return statement, so there is only the one at the very end of the convert function.

jcarpenter2
  • 5,312
  • 4
  • 22
  • 49
-1

There is a basic problem with your code. The while loop will iterate only once as you are returning a value. You should concatenate binaryValue every time with remainder, and return it outside loop. And I haven't checked the logic so do check it.

Ecos
  • 1
  • 1