Wednesday, May 12, 2010

Beware of the \r\n gotcha on Windows

If (as I have just done) you decide to FastFormat to prepare intermediate text for output, and your program runs on Windows, beware of the writeln() and fmtln() API functions. Consider the following code

std::string s;

ff::writeln(s, "hello"); // s => "hello\r\n"

ff::write(std::cout, s); // writes "hello\r\r\n"

This occurs because the underlying C standard library expands each standard end-of-line (EOL) character \n to the Windows-specific EOL sequence \r\n.

Instead, use the *ln() functions on the output, as in:

ff::write(s, "hello"); // s => "hello"

ff::writeln(std::cout, s); // writes "hello\r\n"

No comments:

Post a Comment