rkioji rkioji - 3 months ago 17
C++ Question

Print a string variable with its special characters

When I want to special characters in a string I should use "\":

std::string text("item \t new_item\n")


But, if I print this string, obviously, it will print:

item new_item


Is there a way set std::cout to print all special characters:

item \t new_item \n

Answer

There is no built-in way to do this. You will need to escape characters manually. For example, in C, it'd be something like:

for (const char* p = text; *p != '\0'; ++p)
{
    char c = *p;

    switch (c)
    {
        case '\\':
            printf("\\\\");
            break;
        case '\n':
            printf("\\n");
            break;
        case '\r':
            printf("\\r");
            break;
        case '\t':
            printf("\\t");
            break;

        // TODO: Add other C character escapes here.  See:
        // <https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences>

        default:
            if (isprint(c))
            {
                putchar(c);
            }
            else
            {
                printf("\\x%X", c);
            }
            break;
    }
}