I use the code that allows me to convert any type (int, double, float, char) to string. I tested the program and choose char as type value.
stringstream ss;
string s;
char c = '3';
ss << c;
ss >> s;
cout << "CHAR" << endl;
bitset<8> bs2( (char) c );
for( int i = (int) bs2.size(); i >= 0; i-- )
cout << bs2[i] << " ";
cout << endl;
bitset<8> bs1( (char) s.c_str()[0]);
cout << "STRING" << endl;
for( int i = (int) bs1.size(); i >= 0; i-- )
cout << bs1[i] << " ";
cout << endl;
The output is
CHAR
0 0 0 0 0 0 0 1 1
STRING
0 0 0 0 0 0 0 1 1
But I found one strange thing. I set char c = ' ' and the value was not convert correctly.
CHAR
0 0 0 1 0 0 0 0 0
STRING
0 0 0 0 0 0 0 0 0
I could not find explanation for it and what I did wrong.
operator>>forstd::stringwill only read until the first whitespace character encountered. If you want to extract all of the information in thestd::stringstream, use thestr()member function:For reference see the description of
operator>>(istream& s, string& str)andstringstream::str()