Question

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?

Was it helpful?

Solution

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)
  • ...

OTHER TIPS

\ "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).

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

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

You should try this program:

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

Use a double '\' to escape:

printf("ab\\\0c");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top