Writing a "\n" in a text file

DFE picture DFE · Aug 15, 2011 · Viewed 15k times · Source

I'm trying to write a string \n in a text file. But the result in the text file is a newline. I know that the \n represents a newline. But in my case, I really need to see the String \n, not the newline. How can I solve this?

Answer

Charles Keepax picture Charles Keepax · Aug 15, 2011

The \ character escapes the next character, as you say \n will create a newline. If you wish to output an actual \, you need to write:

"\\n"

That way the first slash escapes the second slash, generating an actual slash rather than escaping the n.