That is, 开发者_如何学JAVAprt("a \t\n")
should print "a \t\n"
literally,
is there any available function that does this?
I am assuming you want to escape special characters; that is, you want to print \n
instead of a newline character.
Not in the standard library, as far as I know. You can easily write it yourself; the core of the function is something like this:
static char *escape_char(char *buf, const char *s) {
switch (*s) {
case '\n': return "\\n";
case '\t': return "\\t";
case '\'': return "\\\'";
case '\"': return "\\\"";
case '\\': return "\\\\";
/* ... some more ... */
default:
buf[0] = *s;
buf[1] = '\0';
return buf;
}
}
/* Warning: no safety checks -- buf MUST be long enough */
char *escape_string(char *buf, const char *s)
{
char buf2[2];
buf[0] = '\0';
for (; *s != '\0'; s++) {
strcat(buf, escape_char(buf2, s));
}
return buf;
}
Generating the function body is also an option, as it can get quite tedious and repetitive.
This is how you can test it:
int main()
{
const char *orig = "Hello,\t\"baby\"\nIt\'s me.";
char escaped[100];
puts(orig);
puts(escape_string(escaped, orig));
return 0;
}
Glib has a function g_strescape() which does this. If the added dependency to glib is not a problem for you, at least.
No, because string literals are already "unescaped" during the parsing of the source code, so the compiler never sees the literal backslashes or quotation marks. You'll just have to escape the backslashes yourself: "\"a \\t\\n\""
.
Alternatively you could take a given string and search and replace all occurrences of control characters by their escape sequence.
You have to escape the backslashes and the quotes with backslashes:
printf( "\"a \\t\\n\"" );
There is not a function as such but you can always
printf("a \\t\\n");
精彩评论