C++ inserting wchar_t backslash into string

2019-07-19 00:48发布

问题:

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?

回答1:

As for your original code

L" !\"#$%&'()*+,-./0123456789:;<=>?\n"

you simply missed escaping the quote character " again. Adding another \ you'll get

L" !\\"#$%&'()*+,-./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.