-1

Why scanf function do not accept escape sequences as an input?

Code

#include <stdio.h>

int main(){
        char str[100];

        printf("Enter value: ");
        scanf("%s", str);

        printf("\nYou Entered: %s", str);

}

Output

Enter value: hello \n world
You Entered: hello

Zafeer
  • 79
  • 7

1 Answers1

3

%s only reads in input up to the first whitespace character - in this case, the space. Thus, it only recognizes "hello", since the rest of the input has not been read.

That being said, scanf can't interpret escaped characters. You could put an actual newline in your input, but you can't use escaped characters and expect it to properly parse them.

In C/C++, if there's a \n in a string literal, it'll be printed as a newline (the compiler does that) but if there's a \n in your input it'll be interpreted literally.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
  • Thanks for the answere...but what should i do to take \n as an input? – Zafeer Jan 07 '20 at 15:40
  • See updated answer - the long and short of it is, you can't. `scanf` doesn't process "\n" as a newline; you'd need to write logic into your program to replace `\n` with an actual newline. – Nick Reed Jan 07 '20 at 15:42