How do i print escape characters as characters?

前提是你 提交于 2019-11-28 06:27:21

问题


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.


回答1:


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



回答2:


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.




回答3:


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!




回答4:


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

printf("%%d"); 


来源:https://stackoverflow.com/questions/6684976/how-do-i-print-escape-characters-as-characters

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