jack excell
jack excell

Reputation: 141

C++ Ofstream a new line

I am trying to do a new line in a ofstream, but it does not work. Everything is written on the same line in OUTPUT.txt

std::ofstream output;
output.open("OUTPUT.TXT");
output << "sometext" << "\r\n" << "sometext" << "\r\n" << "sometext";
output.close();

I also tried

output << "sometext" << std::endl << "sometext" << std::endl << "sometext";

and

output << "sometext" << "\n" << "sometext" << "\n" << "sometext";

and

output << "sometext" << '\n' << "sometext" << '\n' << "sometext";

Everything was written on the same line, no new lines... Am I missing something?

Upvotes: 2

Views: 11663

Answers (4)

Scott Dillman
Scott Dillman

Reputation: 831

In cases like this I find it best to look at the file in a hex editor rather than a text editor that can have its own ideas on how to render text, it also can be good for finding pesky non-printable characters that can trip you up.

You didn't say what platform you are working on, but if you are on windows I would recommend using HxD.

If you are on Windows, you will see something like this:

Offset(h) 00       04       08       0C       10       14       18       1C

00000000  736F6D65 74657874 0D0A736F 6D657465 78740D0A 736F6D65 74657874 0D0A      sometext..sometext..sometext..

The hex sequence 0D0A is the \n character on Windows in the above example.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283614

Probably. You're reading a different copy of the file than the one your program is writing to. Delete the file, then run your program.

Upvotes: 0

Joshua LI
Joshua LI

Reputation: 4733

use

output.open("OUTPUT.TXT", ios::out);

Remind you that ios::binary cannot be used.

Upvotes: 0

lccarrasco
lccarrasco

Reputation: 2051

In case you're using cygwin's g++, it had some issues converting the "\n" to windows-style CRLF under some settings, I tried a simple version of your snippet and it worked fine. Try opening in another text editor and see if the problem persists.

Upvotes: 2

Related Questions