string versus sstream to cout

I am wondering why lots of coding became so enigmatic in c++ since 20 years. Maybe someone can help me with this; it is about output. Three kinds of code flavour should do the same, but they don't. The code simply converts a string of char to binary:
Headers are <string>, <bitset>, <sstream> and <iostream>

Case 1:
1
2
3
4
5
6
7
int main(){
  std::string abc = "abc";
  for (std::size_t i = 0; i < abc.size(); ++i)
  {
    std::cout << std::bitset<8>(abc.c_str()[i]) << std::endl;
  }
}

Gives output: 01100001 '\n' 01100010 '\n' 01100011

Case 2:
1
2
3
4
5
6
7
8
9
int main(){
  std::string abc = "abc";
  for (std::size_t i = 0; i < abc.size(); ++i)
  {
    std::string bitbufstr;
    bitbufstr = std::bitset<8>(abc.c_str()[i]).to_string();
    std::cout << bitbufstr << std::endl;
  }
}

Gives the same output: 01100001 '\n' 01100010 '\n' 01100011

Case 3:
1
2
3
4
5
6
7
8
9
int main(){
  std::string abc = "abc";
  for (std::size_t i = 0; i < abc.size(); ++i)
  {
    std::stringstream bitbufstr;
    bitbufstr << std::bitset<8>(abc.c_str()[i]).to_string();
    std::cout << bitbufstr << std::endl;
  }
}

Outputs: 0xbff870f4 '\n' 0xbff870f4 '\n' 0xbff870f4

What is really worrisome is that the first code doesn't need .to_string()... What does cout do, when and why; is it logic?

Also one should expect as was explained on various sites that stringstream would take the data alike cout. My question is: where is the discrepancy?
Last edited on
One should expect as was explained on various sites that stringstream would take the data alike cout. My question is: where is the discrepancy?

You aren't outputting a string in case 3. You note that stringstream and cout are both streams. So, would you expect std::cout << std::cout; to output everything that has been feed to std::cout? If not, why would you expect it of an instance of std::stringstream?

To get at the data:
std::cout << bitbufstr.str() << std::endl;
Because sstream writes the same to - let's say - a file as cout does. One would expect the input/output formats should be clearly arranged in both. Maybe they are not?
Okay. The streaming bit str(). Sorry
Because sstream writes the same to - let's say - a file as cout does. One would expect the input/output formats should be clearly arranged in both. Maybe they are not?

You were not comparing the "output" of the string formatted by the stringstream to the output produced by "cout".

cire wrote:
To get at the data:
std::cout << bitbufstr.str() << std::endl;
Topic archived. No new replies allowed.