0

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?

user229044
  • 232,980
  • 40
  • 330
  • 338
cong
  • 41
  • 2
  • 4
  • 6
    Are we going to get a lot of these from you? –  May 05 '11 at 21:18
  • Because \\ will output a single \. You can use `std::endl` to get the effect you want: `std::cout << "what is the output" << std::endl << "hello \'world\' world";` – Sitnik May 05 '11 at 21:19
  • 2
    @cong: he means that this is a fairly basic question that any good C++ book would give you answers too, and for learning C++ that is still the best option, a good book. – Tony The Lion May 05 '11 at 21:21
  • I guess that @unapersson means that this question, as well as your previous one, is rather basic. You might benefit from reading through some good introductory books or tutorials on c++. Then most of these questions will be automatically answered for you. Hope that helps. ;) – Bart May 05 '11 at 21:22
  • @sitnik: `endl` will also flush the stream, which often is not what you want. – Matteo Italia May 05 '11 at 21:26
  • 1
    Why is everyone jumping in to say what (they think) I mean? For all they know, I may be looking forward with rapt attention for more posts from this user. –  May 05 '11 at 21:30
  • And there are lots of good books listed athere: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. – Robᵩ May 05 '11 at 21:30

2 Answers2

10

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

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
4

\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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466