How do i print escape characters as characters?

前端 未结 4 808
闹比i
闹比i 2020-12-20 02:17

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

while((c = fgetc(fp))!= EOF)
{
    if(c == \'\\0\')
    {
        printf(\"          


        
相关标签:
4条回答
  • 2020-12-20 02:52

    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. */
    }
    
    0 讨论(0)
  • 2020-12-20 02:53

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

    printf("%%d"); 
    
    0 讨论(0)
  • 2020-12-20 03:03

    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!

    0 讨论(0)
  • 2020-12-20 03:06

    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.

    0 讨论(0)
提交回复
热议问题