Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using printf without having to escape double quotes?

Tags:

c

printf

In C it is not normally possible to use ' for printf of a string. However, I have text which are full of double quote ", and I need to escape all of them as

printf("This is \"test\" for another \"text\"");

Is it possible to printf in a way without escaping ". I mean using another character for wrapping the string.

like image 643
Googlebot Avatar asked Oct 26 '25 03:10

Googlebot


1 Answers

Not recommended, but you can use a macro:

#include <stdio.h>
#define S(x) #x

int main() {
    printf(S(This "is" a string (with nesting)!\n));
}

This prints

This "is" a string (with nesting)!

Now the delimiters are balanced () characters. However, to escape single ), ", or ' characters, you have to write something like S(right paren: ) ")" S(!\n), which is quite ugly. This technique is not recommended for writing maintainable code.

like image 106
nneonneo Avatar answered Oct 29 '25 08:10

nneonneo