打印带有特殊字符的字符串变量 [英] Print a string variable with its special characters

查看:70
本文介绍了打印带有特殊字符的字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想在字符串中使用特殊字符时,我应该使用\":

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

有没有办法设置 std::cout 来打印所有特殊字符:

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

item \t new_item \n

推荐答案

没有内置的方法可以做到这一点.您将需要手动转义字符.例如,在 C 中,它会是这样的:

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)
{
    int c = (unsigned char) *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;
    }
}

(请注意,我在问题仍然用 C 标记时写了上面的答案,我使用了 printf 因为我发现它比通过 C++ 的 iostream 格式更简单(尤其是出于演示目的)机制.)

(Note that I wrote the above answer while the question was still tagged with C, and I used printf because I find it to be simpler (especially for demonstrative purposes) than going through C++'s iostream formatting mechanism.)

这篇关于打印带有特殊字符的字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆