Hey everyone,
Im new here, i have been browsing round these forums for awhile and thought i would get involved. Anyway i have a slight problem... I have a little bit of code that changes a string (eg. john) into its binary representation.
What is going wrong, is that my code combines all the ASCII values for each letter instead of keeping them seperate and then converting each ASCII value to its binary equivalent.

Here is what i have got:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void decToBin(int number, int base);
int main()
{
    int decimalNumber;
    int base;
    int answer=0;
    int digit;
    base = 2;
    cout<<"Enter a string: ";
    string name;
    getline(cin,name);
    for (int i=0; i<name.size(); i++)
    {
            answer = answer *10;
            digit = int(name[i])-int("0");
            answer = answer + digit;   
    }
 
    decimalNumber=answer;
    cout<<"Decimal "<<decimalNumber<<" = ";
    decToBin(decimalNumber, base);
    cout<<" Binary"<<endl;
    system("PAUSE");
    return 0;
}    
void decToBin (int number, int base)
{
     if (number>0)
     {
        decToBin(number/base, base);
        cout<<number%base;
     }
}

My output i am trying to get to is:
J binary (binary value here)
o binary (binary value here)
h binary (binary value here)
n binary (binary value here)

But as you can see i am struggling, any help would be appreciated thanks :)

Recommended Answers

All 2 Replies

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void decToBin(int number, int base);
int main()
{
   cout<<"Enter a string: ";
   string name;
   getline(cin,name);
   for (unsigned int i=0; i<name.size(); i++)
   {
      cout << name[i] << " binary (";
      decToBin(name[i], 2);
      cout << ")" << endl;  
   }
   return 0;
}    
void decToBin (int number, int base)
{
     if (number>0)
     {
        decToBin(number/base, base);
        cout << number%base;
     }
}

ah cheers mate, much appreciated!!!
i need to think more logically - thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.