How to write '\' to output stream

closed account (EwCjE3v7)
I forgot but how can I print our '\' again?

 
  cout << "\" << endl; // dosn`t work 
It's special character. You have to put "\\" instead. :)

Explanation:
In C(and because C++ originated from C, also in C++, and some other languages), there are some "special characters". They always represent some functionality.

I hope that you made it through strings. If so, then you should already know, that each C-string is null-terminated - it ends with '\0' character. This character will not be shown, but it's there to tell computer "Hey. You arrived to the end of the string, stop reading now". Otherwise your program would read some trash data that sits later. You don't have to worry about null character, most of the time - when you create string(like: "String"), compiler automagically puts null character at the end :).

That's also the reason why every string you want to store, that is N characters long, has to be N+1 size big. You have to include a space for null character.

But there comes the problem. We wanted to use a null character, so we needed a way to distinguish null terminator from simple '0', an integer. Programmers did that by using '\' character. It changes the way next character will behave. So, if you put '\0', it will not be treated as '0', but as a null terminator.
It works for few other things, like what should you do when you want to insert quotation mark into your string? You use '\' sign(text would look like this: " He said \"You're annoying.\".").
And for the same reason, if you want to see '\', you have to use '\\'. :)

I hope you got it.

Cheers!
Last edited on
If there are many of them, a raw string literal comes in handy.

std::cout << R"(raw string literal with quotes and "backslash" \c\h\a\r\a\c\t\e\r\s\.)" << '\n' ;

http://www.stroustrup.com/C++11FAQ.html#raw-strings
Topic archived. No new replies allowed.