(a)
string str = "Hello\nWorld";
When I print str
, the output is:
Hello
World
(b)
string str;
cin >> str; //given input as Hello\nWorld
When I print str
, the output is:
Hello\nWorld
What is the difference between (a) and (b)?
The C++ compiler has certain rules when control characters are provided - documentation. As you can see, when you specify
\n
in a string literal it is replaced by the compiler with a line feed (value 0xa for ASCII). So instead of 2 symbols,\
andn
, you get one symbol with binary code 0xa (I assume you use ASCII encoding), which makes the console move output to a new line when printed. When you read a string the compiler is not involved and your string has the actual symbols\
andn
in it.Because stream readers are defined to be that way. At the core, each character is read separately. Only higher level functions provided additional meaning to the characters.
When a compiler processes the string literal
"Hello\nWorld"
, its file reader passes it two characters too. Only the C++ compiler/parser translates them into one character based on the rules of the language.Escape characters in a string are interpreted by the compiler. The sequence
\n
consists of two actual characters, which the compiler converts to a single newline character during compilation. The same sequence is not interpreted in any way when you enter it on the command line, so results in the exact two characters that you entered.If you want to process your string to interpret escape sequences, you will have to do it yourself (or use an appropriate library).
When specified in a string literal, "\n" will be translated to the matching ascii code (
0x0a
on linux), and stored as-is. It will not be stored as a backslash, followed by a literaln
. Escape sequences are for you convenience only, to allow string literals with embedded newlines.On the other hand, your shell, running in the terminal, does not do such substitution: it submits a literal backslash and
n
, which will be printed as such.To have a newline printed, enter a newline:
The string on cout<<"Hello\nworld" it's converted by the compiler to a compiled string where escape codes are converted to characters, so the cout function when executed does not see a two char "\n" string but the equivalent code for next line character.
But the cin gets the string of every typed character at runtime and does not convert escape codes. So if you want to convert those escape codes you have to make a replace function.
In compiled code the character literal
’\n’
is replaced by an implementation-specific value that the runtime system treats as a newline character. The language definition does not require any particular value.When reading input from the console or a file the incoming text is not being compiled, and the character sequence “\n” does not have any special meaning. It is simply two characters.