escapping \n, \t etc.

P

Prasad

Hi All,

If the string is say, str = "Hello\nWorld" ;
Now, when I call printf ( "%s", str) ;
It is printed as
Hello
World.

But I want it to be printed as "Hello\nWorld". Hence, I need to escape
the \n with an extra \ ie. \n should be replaced with \\n.

What is the best way to do it? for all \n, \t, \b etc

Thanks and regards,
Prasad.
 
R

Richard Heathfield

Prasad said:
Hi All,

If the string is say, str = "Hello\nWorld" ;
Now, when I call printf ( "%s", str) ;
It is printed as
Hello
World.

But I want it to be printed as "Hello\nWorld". Hence, I need to escape
the \n with an extra \ ie. \n should be replaced with \\n.

What is the best way to do it?

Like you just did it.

#include <stdio.h>

int main(void)
{
char str[] = "Hello\\nWorld";
printf("%s\n", str);
return 0;
}

Output:
Hello\nWorld
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top