How do i print escape characters as characters?

user798774 picture user798774 · Jul 13, 2011 · Viewed 23.1k times · Source

I'm trying to print escape characters as characters or strings using this code:

while((c = fgetc(fp))!= EOF)
{
    if(c == '\0')
    {
        printf("   \0");
    }
    else if(c == '\a')
    {
        printf("   \a");
    }
    else if(c == '\b')
    {
        printf("   \b");
    }
    else if(c == '\f')
    {
        printf("   \f");
    }
    else if(c == '\n')
    {
        printf("   \n");
    }
    else if(c == '\r')
    {
        printf("   \r");
    }
    else if(c == '\t')
    {
        printf("   \t");
    }
    else if(c == '\v')
    {
        printf("   \v");
    }
}

but when i try it, it actually prints the escape sequence.

Answer

cnicutar picture cnicutar · Jul 13, 2011

Escape the slashes (use " \\a") so they won't get interpreted specially. Also you might want to use a lookup table or a switch at least.

switch (c) {
case '\0':
    printf("   \\0");
    break;
case '\a':
    printf("   \\a");
    break;
/* And so on. */
}