5

I am trying to use a ostringstream to build a string which uses the platform standard line endings (so for me it is CRLF since I am developing for Windows). I tried the following code:

std::ostringstream out;
out << "line1\nline2\n";
const char* result = out.str().c_str(); // In result end of lines are '\n' instead
                                        // of the expected '\r\n'

Since ostringstream is opened by default in text mode, I thought it would perform the end of line conversion (like an ofstream) but the resulting char buffer does not contain the expected CRLF end of lines....

Edit:

For those who wondered why I needed the CRLF ending internally: I copy the text into the Windows clipboard and user often copy that content to Notepad and without the CRLF ending the end of lines are lost during that last operation....

My solution:

Finally I decided to use the boost library to replace \n with \r\n:

boost::replace_all( str, "\n", "\r\n" );
JMD
  • 218
  • 1
  • 2
  • 6
  • That is correct. `std::ostringstream` uses internal text string representation. CRLF is used for the on-disk text representation. If you read the `std::ifstream` to `std::string` you expect that CRLF is converted to internal representation. So everyone expects that `std::string` contains internal text representation at any moment. – Serge Dundich Mar 29 '11 at 08:38
  • Just to complete the above solution for the case that you already have mixed line endings: `boost::replace_all( str, "\n", "\r\n" );` `boost::replace_all( str, "\r\n\n", "\r\n" );` – Frank Heimes Dec 13 '22 at 16:09

2 Answers2

2

Well, '\n' is the internal representation for end-of-line.

It is just when you write to an external file that it is converted (if needed!) to the external representation. On some systems the line ending is just one character, or even no character at all if stored with a hidden length value instead.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

The distinction text mode/binary mode is purely std::filebuf. It's not relevant elsewhere.

I'm not sure why you would want anything but "\n" in an internal string, but it's not difficult: just define

char const newline[] = "\x0D\x0A";  //  Or whatever the convention is

and output that.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • I hoped it would also be able to perform the conversion without creating a file. Well I guess I will simply add a newline parameter to my function, thanks to everyone. – JMD Mar 29 '11 at 08:39