Reputation: 650
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.
Upvotes: 1
Views: 1532
Reputation: 2239
The >>
operator won't return the space, use ss.str();
to get the stringstream value.
Upvotes: 2
Reputation: 8116
operator>>
for std::string
will only read until the first whitespace character encountered. If you want to extract all of the information in the std::stringstream
, use the str()
member function:
s = ss.str();
For reference see the description of operator>>(istream& s, string& str)
and stringstream::str()
Upvotes: 3