x86
x86

Reputation: 123

Is there a function to print string as is in escaped mode?

That is, prt("a \t\n") should print "a \t\n" literally,

is there any available function that does this?

Upvotes: 0

Views: 164

Answers (5)

Danilo Piazzalunga
Danilo Piazzalunga

Reputation: 7844

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;
}

Upvotes: 6

harald
harald

Reputation: 6126

Glib has a function g_strescape() which does this. If the added dependency to glib is not a problem for you, at least.

Upvotes: 6

rerun
rerun

Reputation: 25505

There is not a function as such but you can always

printf("a \\t\\n");

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477590

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.

Upvotes: 4

dandan78
dandan78

Reputation: 13925

You have to escape the backslashes and the quotes with backslashes:

printf( "\"a \\t\\n\"" );

Upvotes: 1

Related Questions