Coverting std::string to binary

I want to convert an std::string to binary, but I'm having problems. I tried using std::bitset to do it, but I can't get it to work. It may just be because I'm using an online compiler to test it, because I'm at school and don't have access to a compiler.

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Binary Compatibility Program
//Based on many programs on the internet

#include <iostream>
#include <bitset>
#include <string>

int main()
{
    std::string name1;
    std::string name2;
    std::cout << "This program will calculate how good a match to people's name's are.\n";
    std::cout << "Guys Name: ";
    std::cin >> name1;
    std::cout << "Girls Name: ";
    std::cin >> name2;
    std::bitset<8> binaryName1(name1);
    std::bitset<8> binaryName2(name2);
    std::cout << binaryName1 << " " << binaryName2;
}
You can't do it that way, bitsets created by strings except the strings to only have 1s and 0s. Maybe you could try something like getting the data address and using that to initialize it (as a ulong).
You can try the Boost lib . first convert the string to a number then convert the number to a binary number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <boost/lexical_cast.hpp>
#include <string>

int main()
{
    std::string str = "5";
    int  strVal;
    try {
        strVal = boost::lexical_cast<int>(str);
    } catch(bad_lexical_cast&) {
        //Do your errormagic
    }
    return 0;
}


Topic archived. No new replies allowed.