user3618641
user3618641

Reputation: 33

How to print "\\0" in C language

I wanted to print \0 using printf. First I found printf("ab\0c") is not right because I can only get "ab". Then I found a way to print "ab\0c" using printf("ab\\0c"). But that brings a new problem. What if I want to print "ab\\0c"? I want to print it in only one sentence. Do you have any good way to do this?

Upvotes: 2

Views: 5059

Answers (5)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6003

Use a double '\' to escape:

printf("ab\\\0c");

Upvotes: 0

John3136
John3136

Reputation: 29266

\ "escapes" special characters (allows you to write \n and \" etc). If you want to print a \ you need to escape that (since \ is a special character itself). Put \\ in your string to print \.

If you want to print \\ your format string has to be \\\\ (i.e. escape both \s).

Upvotes: 3

Sam
Sam

Reputation: 11

You should try this program:

printf("ab\\\\0c");

Upvotes: 1

Eugen Rieck
Eugen Rieck

Reputation: 65264

Printing a single backslash (as opposed to using it as an escape sequence) needs a double backslash to undo the escaping., so basically

  • If you want to print ab\0c you need printf("ab\\0c") (2 times 1 is 2)
  • If you want to print ab\\0c you need printf("ab\\\\0c") (2 times 2 is 4)
  • ...

Upvotes: 7

Yu Hao
Yu Hao

Reputation: 122383

One \\ prints one \, to print \\, use:

printf("ab\\\\0c");

Upvotes: 1

Related Questions