MNY
MNY

Reputation: 1536

Is it possible to print non-printing characters with a %C specifier?

Is it possible to use a function to detect non-printing characters with isctrl() and use printf with %C specifier to print them as '\n' for instance?

Or I should write an if for every control caracter and printf("\\n") for instance..?

OK, thanks to All of the kind people below - it is not posible, you HAVE to specify each situation. example:

if (isctrl(char))// WRONG
 printf("%c", char);

if (char == '\n')//RIGHT, or using switch. 
 printf("\\n");

Upvotes: 8

Views: 17696

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409166

To expand on the answer by Aniket, you could use a combination of isprint and the switch-statement solution:

char ch = ...;

if (isprint(ch))
    fputc(ch, stdout);  /* Printable character, print it directly */
else
{
    switch (ch)
    {
    case '\n':
        printf("\\n");
        break;

    ...

    default:
        /* A character we don't know, print it's hexadecimal value */
        printf("\\x%02x", ch);
        break;
    }
}

Upvotes: 10

Rakesh Burbure
Rakesh Burbure

Reputation: 1045

You can determine the non-printing character, but i dont think so, you can write those characters. You can detect specific non printing characters by observing their ASCII value.

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25705

const char *pstr = "this \t has \v control \n characters";
char *str = pstr;
while(*str){
   switch(*str){
     case '\v': printf("\\v");break;
     case '\n': printf("\\n"); break;
     case '\t': printf("\\t"); break;
     ...
     default: putchar(*str);break;
   }
   str++;
}

this will print the non-printable characters.

Upvotes: 11

Related Questions