开发者

Problem with iostream, my output endl are littles squares

开发者 https://www.devze.com 2022-12-21 10:32 出处:网络
I have a problem with with my output when I write to I file I get squares开发者_如何学编程 when I put endl to change lines.

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?


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;


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消