有没有办法将字符串打印为文字?
Is there a way to print a string as a Literal?
如你所知,我们可以使用这样的东西:
string s = L("some\nstr\t");
我的问题是是否有办法使用文字打印字符串。例如这样的事情:
string s = "s\nsome\n"
cout<< L(s); // the output printed should be s\nsome\n and not new lines
谢谢。
是的,
string s = "Here is \nan \n example"
cout<< s;
Francois 的回答已经很好了,但我想详细说明这里发生的事情...
当你把\n
放在一个字符串中时,就是一个字符。 \
表示 "don't treat whatever comes next as you normally would, escape it." 转义的 n
是换行符,因此 \n
是换行符。
所以如果你想在你的字符串中使用 \
,你会如何得到它?通常这被视为转义字符,但我们希望它只是一个普通字符。那我们该怎么做呢?我们躲开它! \
将被解释为单个 \
字符。
所以如果你想打印s\nsome\n
,你需要将你的字符串构造为"s\nsome\n"
。请注意,n
没有被转义,转义字符是!
如你所知,我们可以使用这样的东西:
string s = L("some\nstr\t");
我的问题是是否有办法使用文字打印字符串。例如这样的事情:
string s = "s\nsome\n"
cout<< L(s); // the output printed should be s\nsome\n and not new lines
谢谢。
是的,
string s = "Here is \nan \n example"
cout<< s;
Francois 的回答已经很好了,但我想详细说明这里发生的事情...
当你把\n
放在一个字符串中时,就是一个字符。 \
表示 "don't treat whatever comes next as you normally would, escape it." 转义的 n
是换行符,因此 \n
是换行符。
所以如果你想在你的字符串中使用 \
,你会如何得到它?通常这被视为转义字符,但我们希望它只是一个普通字符。那我们该怎么做呢?我们躲开它! \
将被解释为单个 \
字符。
所以如果你想打印s\nsome\n
,你需要将你的字符串构造为"s\nsome\n"
。请注意,n
没有被转义,转义字符是!