cong
cong

Reputation: 41

Why does this code output a literal "\n" instead of a newline?

What is the output of this following code?

std::cout<<"what is the output \\n hello \'world\' world";

I think the output should be:

what is the output
hello 'world' world

But the actual output is the output \n hello 'world' world

Why isn't \n output as a new line?

Upvotes: 0

Views: 4271

Answers (2)

Jonathan Wood
Jonathan Wood

Reputation: 67193

\n specifies a new line character. But what happens if you want a backslash character? For this, C++ allows you to use \\. The first backslash escapes the second resulting in a single backslash and no special translation.

That's what you have here, followed by n.

Upvotes: 4

Ben Jackson
Ben Jackson

Reputation: 93720

Your double backslash \\ is an escape that produces \ so you see \n. If you want a newline, use a single backslash \n.

Upvotes: 10

Related Questions