C ++将wchar_t反斜杠插入字符串 [英] C++ inserting wchar_t backslash into string
问题描述
我有一个宽字符:
const wchar_t * charSet = L!\#$%& '()* +, - 。/ 0123456789:;?=??\\\
/ pre>
L@ABCDEFGHIJKLMNOPQRSTUVWXYZ [\\] ^ _ \\\
L`abcdefghijklmnopqrstuvwxyz当我把它传递到文本处理器'\'('\\\\\\\\\\\\\\\\\\\\\\\\\\反斜杠)不存在。现在如果我改为\\它
我得到编译时错误:
缺少关闭引用
那么如何将反斜杠放入这样的char字符串?
解决方案至于您的原始代码
code> L!\#$%&'()* +, - 。/ 0123456789:;< =>?\\\
您再次错过转义引号字符
您会得到
L!\\#$%&' )* +, - 。/ 0123456789:;??\\\
现在未转义的
在此时关闭文本。下一次出现的
将打开一个新的文本,但它是不平衡的,因此编译器错误消息(你可以发现效果,甚至在这里的代码标记)。你需要添加再次转义
\
以转义:
L!\\\#$%&'()* +, - 。/ 0123456789:;< =>?\\\
// ^^^修复此问题
与
\
反斜杠和引号字符混合的转义字符很难阅读和维护更改。 p>
由于最新的标准( c ++ 11 )你可以使用 原始字符字符串文字 :
#include< iostream&
#include< string>
int main(){
std :: wstring ws(LRdel(!\#$%&'()* +, - 。/ 0123456789:;& =>?)delL\\\
LRdel(@ABCDEFGHIJKLMNOPQRSTUVWXYZ [\] ^ _)delL\\\
LRdel(`abcdefghijklmnopqrstuvwxyz { }〜)delL\\\
);
std :: wcout return 0;
}
输出
!\ &'()* +, - 。/ 0123456789:;" =?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ [\] ^ _
`abcdefghijklmnopqrstuvwxyz {|}〜
I have a wide char literal:
const wchar_t* charSet = L" !\"#$%&'()*+,-./0123456789:;<=>?\n" L"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\n" L"`abcdefghijklmnopqrstuvwxyz{|}~\n";
When I pass it into text processor '\'(backslash) isn't there.Now if I put instead \\ it
I am getting compile time error:
"missing closing quote"
So how do I put backslash into such a char string?
解决方案As for your original code
L" !\"#$%&'()*+,-./0123456789:;<=>?\n"
you simply missed escaping the quote character
"
again. Adding another\
you'll getL" !\\"#$%&'()*+,-./0123456789:;<=>?\n"
and the now unescaped
"
closes the literal at this point. The next occurrence of"
will open a new literal but it's unbalanced, hence the compiler error message (you can spot the effect even in the code markup here). You need to add a further\
to escape the"
again:L" !\\\"#$%&'()*+,-./0123456789:;<=>?\n" // ^^^ Fix this
But managing escaped characters intermixed with
\
backslash and"
quote characters is pretty hard to read and to maintain with changes.Since the latest standard (c++11) you can make use of raw character string literals:
#include <iostream> #include <string> int main() { std::wstring ws(LR"del( !\"#$%&'()*+,-./0123456789:;<=>?)del" L"\n" LR"del(@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_)del" L"\n" LR"del(`abcdefghijklmnopqrstuvwxyz{|}~)del" L"\n"); std::wcout << ws; return 0; }
Output
!\"#$%&'()*+,-./0123456789:;<=>? @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ `abcdefghijklmnopqrstuvwxyz{|}~
No escaping necessary, you see.
See the working samples here and here for compilers supporting the current standards.
这篇关于C ++将wchar_t反斜杠插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!