dark_shadow
dark_shadow

Reputation: 3573

Why does "\n" display different when entered on stdin instead of from code?

Suppose I have an array of characters char str[10].

If I store the value xyz\nabc in str using char str[10]="xyz\nabc"; and output it, it gives the following output:

xyz
abc

On the other hand, if I give it input from stdin in the form xyz\nabc and then print it, it gives the following output:

 xyz\nabc

Why is it so?

Upvotes: 1

Views: 139

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

When you read it from stdin, you get exactly the string "xyz\nabc", as it appears.

If you hard-code that value in the code (i.e. char* x = "xyz\nabc"), the \n is a single character, and it represents a new line. To get the same output, you need char* x = "xyz\\nabc" - the extra \ escapes the \.

See this http://en.cppreference.com/w/cpp/language/escape

Upvotes: 7

Related Questions