1

Since std::stringstream is a stzream, and according to the documention here, you can perform any operation a stream supports.

So I expected the following sample to work, but it seems it doesn't. I'm using MingW with gcc 4.8.3.

Variant A:

std::string s;
std::stringstream doc;
doc << "Test " << "String ";
doc << "AnotherString";
doc >> s;
std::cout << s << std::endl;

Variant B:

std::string s;
std::stringstream doc;
doc << "Test ";
doc << "AnotherString";
doc >> s;
std::cout << s << std::endl;

The output of this is only

Test 

While I expected that it would concatenate the individual strings until I read from the stream back what I put there.

So what is the approperiate way to concatenate strings? Do I really have to read out each one individually and concatenate them manually, which seems quite awkward to me in C++.

Devolus
  • 21,661
  • 13
  • 66
  • 113
  • `stream >> s` only reads one word from the stream. It doesn't matter what kind of stream it is. Use `getline` if you want the whole line instead of one word. – Barmar Feb 03 '14 at 12:37

2 Answers2

2

It is putting each of the strings into doc, so that its content is:

Test String AnotherString

Then when you extract using doc >> s, it only reads up to the first whitespace. If you want to get the entire stream as a string, you can call str:

std::cout << doc.str() << std::endl;
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • @Devolus If you know it's all going to be one line in the stream, you can do `std::getline(doc, s);`. If not, you could do `std::istreambuf_iterator eos; std::string s(std::istreambuf_iterator(doc), eos);` to get the entire content of the stream. – Joseph Mansfield Feb 03 '14 at 13:00
  • Yeah, it's only one line per loop. I found an answer hwo to clear the stream here: http://stackoverflow.com/questions/20731/in-c-how-do-you-clear-a-stringstream-variable so for completeness it would be good to add this link to the answer, as the behaviour is q bit different as might be expected if the stream is not cleard when reading the content. I suppose getline does this? – Devolus Feb 03 '14 at 13:03
  • @Devolus `getline` will extract. Sure, you could do `str()` and then clear, that's one solution. – Joseph Mansfield Feb 03 '14 at 13:07
1

It will only read one word till a white-space by using stream >> s. Besides @JosephMansfield's answer of using str(), alternatively you can use getline() (works perfectly if you the string doesn't contains new lines):

getline(doc, s);
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174