Search code examples
c++cformatted

Console output of strings with special characters


Is there a more or less standard way to output character strings that contain special characters, such ASCII control codes, in such a way that the output is a valid C/C++ literal string, with escape sequences ?

Example of expected output: This\nis\na\\test\n\nShe said, \"How are you?\"\n

Without care, the output would be

This
is
a\test

She said, "How are you?"

not what want.


Solution

  • Depending on what you might be trying to achieve I can suggest the following solution: Just replace any non-printable character with "\xnn" (nn being the ascii code of the character. This would boil down to

    void myprint (char *s) {
       while (*s) {
          printf(isalnum((unsigned char) *s) ? "%c" : "\\%03hho", *s);
          s++;
       }
    }
    

    This will of course not use special abbreviations like \n (but \x0a) instead, but this shouldn't be a problem.