tags:

views:

98

answers:

3

I have a problem with with my output when I write to I file I get squares when I put endl to change lines.

std::ofstream outfile   (a_szFilename, std::ofstream::binary);
outfile<<"["<<TEST<<"]"<<std::endl;

I get something like this in my file plus the other outputs don't write on the next line but on the same one.

[TEST]square

apparently I can't write the square here, but is it something about the ofstream being binary or something?

+5  A: 

You don't really want to open the file in binary mode in this case.

Try this instead:

std::ofstream outfile   (a_szFilename);
outfile<<"["<<TEST<<"]"<<std::endl;
Jeff Wilhite
I don't think this should be down-voted, it's correct. Formatted output and binary don't go together.
GMan
+3  A: 

You're opening the file in binary mode. in this case the endl is written as \n while a newline on windows is supposed to be \r\n

To open you file in text mode just don't include the binary flag the translation will be done automatically

std::ofstream outfile(a_szFilename);
outfile<<"["<<TEST<<"]"<<std::endl;
f4
What mode should I use then?
Apoc
+2  A: 

It's probably because you're in binary mode and the line endings are wrong. std::endl will place '\n' on the stream before flushing. In text mode, this will be converted to the correct line ending for your platform. In binary mode, no such conversions take place.

If you're on Windows, your code will have a line feed (LF), but Windows also requires a carriage return (CF) first, which is '\r'. That is, it wants "\r\n", not just a newline.

Your fix is to open the file in text mode. Binary files are not suppose to be outputting newlines or formatted output, which is why you don't want to use the extraction and insertion operators.

If you really want to use binary, then treat your file like a binary file and don't expect it to display properly. Binary and formatted output do not go hand in hand. From your usage, it seems you should be opening in text mode.

GMan