Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i print escape characters as characters?

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.

like image 938
user798774 Avatar asked Oct 23 '25 15:10

user798774


2 Answers

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. */
}
like image 72
cnicutar Avatar answered Oct 25 '25 06:10

cnicutar


Backslashes in string literals need to be escaped; instead of "\0", you need "\\0".

A lookup table might make this less painful:

const char *ecs[256] = {NULL}; // assumes ASCII - may not be a valid assumption
int c;

ecs['\0'] = "\\0";
ecs['\a'] = "\\a";
ecs['\b'] = "\\b";
...
while ((c = fgetc(fp)) != EOF)
{
  if (ecs[c] == NULL)
    printf("%c", c);
  else
    printf("%s", ecs[c]);
}

Yes, the majority of entries in ecs are going to be NULL; the tradeoff is that I don't have to worry about mapping the character value to array index.

like image 24
John Bode Avatar answered Oct 25 '25 05:10

John Bode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!