(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)?
Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.
C++ assigns special meaning to the backslash within a string literal and requires it to be escaped to be read as an actual backslash: To represent a single backslash, it's necessary to place double backslashes (\\) in the source code. (Exception: Raw literals, supported by C++11, remove the need to escape characters.)
As mentioned in the introduction, the action of escaping characters means you write an “escape sequence” to represent specific characters. An escape sequence starts with a \. It is followed by a character or a series of numbers representing the Unicode character code. When we run the previous code, we obtain the following result:
An escape sequence starts with a \. It is followed by a character or a series of numbers representing the Unicode character code. When we run the previous code, we obtain the following result: If we take a closer look: We can write \" to insert a " character inside a string, which would be impossible otherwise.
In my opinion, the most helpful special characters are: var q = '\''; (not covered yet). See preceding example. See preceding example. See preceding example. See String Escape Sequences for some more characters. Next, we explore line break. In case you did not know, Windows line breaks are different from Unix-based platforms.
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, \
and n
, 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 \
and n
in it.
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 literal n
. 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:
$ echo "Hello World" | ./your-program
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With