在 C++ 中分配给类型 char (不是 String)时如何转义字符
我正在阅读类似于此讨论的内容所以上周现在我遇到了找不到该线程的问题。
我需要将双引号字符 " 分配给类型为 wchar_t
的变量,我使用
wchar_t atest = '"';
wchar_t atest2 = '\"';
在 VS 调试器中 atest
显示为 34 L'"' (现在我看到引号分开的位置),并且
atest2
是 38 L'&'
。我现在知道该使用哪个,但不知道为什么。当我创建 atest2
时发生了什么?
I was reading similar to this discussion here on SO last week and now I have the problem I can't find that thread.
I need to assign the double quote character " to a variable of type wchar_t
, I use
wchar_t atest = '"';
wchar_t atest2 = '\"';
In the VS debugger atest
is shown as 34 L'"'
(now I see where the quotes separate) and atest2
is 38 L'&'
. I understand which to use now but not why. What is happening when I create atest2
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两者是等价的。
某些字符必须在字符文字中转义,包括
\
本身,因此反斜杠字符是'\\'
。双引号字符可以可选被转义。据推测,这是为了与字符串文字保持一致,它们必须被转义。类似地,单引号字符必须在字符文字中转义,并且可以在字符串文字中转义。
(不,
'\"'
不是多字符常量。)These two are equivalent.
Certain characters have to be escaped in character literals, including
\
itself, so a backslash character is'\\'
.The double-quote character can optionally be escaped. Presumably this is for consistency with string literals, where they must be escaped. Similarly, the single-quote character must be escaped in character literals, and may be escaped in string literals.
(No,
'\"'
is not a multi-character constant.)你拥有的是一个多字符常量。根据 C(++) 规范,它们是合法的,但它们的解释是实现定义的。有关详细信息,请参阅 MSDN,但简而言之:不要不要那样做。
What you have is a multi-character constant. They are legal per the C(++) specifications but their interpretation is implementation-defined. See MSDN for a little bit of detail, but in short: don't do that.