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.
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.
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");
精彩评论