6

We know that when inserting \n in a file stream, the appropriate end-of-line sequence for the system will be written to the file (e.g. \r\n for Windows). Does inserting an endline in a std::stringstream result in the system-appropriate end-of-line sequence being written to the string? For example:

#include <sstream>

int main()
{
    std::ostringstream oss;
    oss << std::endl;
    std::string endlineSequence = oss.str();
    bool isWindows = enlineSequence == "\r\n";
    bool isOldMac  = endlineSequence == "\r";
    bool isUnix    = endlineSequence == "\n";
    // Will this work???
}
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
  • 1
    To save your time, you can execute and see if all the `bool`s in your program are `true` or not... most likely `isWindows` and `isMac` will evaluate to `false`. – A. K. Jul 28 '11 at 20:49
  • @Aditya: I'd have to try on each platform. Not everyone has a Windows, Mac, and Unix box at their disposal. :-) – Emile Cormier Jul 28 '11 at 20:52
  • @Emile: no, you only need to try it in Windows. Because if you write `\n` and get `\r\n`, it does the translation to native newline; and if you get `\n` it doesn't. It's not noticeable in Linux or MacOS X, though. – R. Martinho Fernandes Jul 28 '11 at 21:00
  • 1
    on both windows and linux machines, isUnix evaluates to true. – A. K. Jul 28 '11 at 21:06
  • @Aditya: Thanks. That validates Björn's answer. – Emile Cormier Jul 28 '11 at 21:23

2 Answers2

15

The system specific line endings are only relevant for text files. As long as the stream is only in memory, it is just '\n'.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 6
    How can it be anything but the single character '\n' in a string stream? Suppose the translation was done on a string stream. Think of the mess that would result with `sstream1 << "\n"; sstream2 << stream1.str(); ...; std::cout << sstream99.str();` – David Hammen Jul 28 '11 at 21:00
  • Works also for Windows OutputDebugStringA – TarmoPikaro Nov 30 '18 at 05:37
3

Short answer: No.

Long answer:

The file stream in text mode will insert a platform specific ELS into the file. But the application will never see this as the ELS is converted back into \n when the file is read. So even with file stream (in text mode) you will never see the ELS.

Back to the std::stringstream. If the code did insert a platform specific ELS (which it does not) then when you read the stream you would still expect to see \n when you read it back as you would expect the ELS to be converted back. There is little point in doing so.

fduff
  • 3,671
  • 2
  • 30
  • 39
Martin York
  • 257,169
  • 86
  • 333
  • 562