How do i print escape characters as characters?

前端 未结 4 1686
花落未央
花落未央 2020-12-20 02:32

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

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


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 02:52

    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.

提交回复
热议问题