How do i print escape characters as characters?

血红的双手。 提交于 2019-11-29 12:36:44

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. */
}

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.

aibk01

For that we need to use double backslash.

Examples:

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

Should work for you!

If you want to escape %d within printf to allow you to actually print the characters "%d":

printf("%%d"); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!