如何使用L前缀作为未加引号的字符串

how can I use L prefix to unquoted string?

本文关键字:加引号 字符串 何使用 前缀      更新时间:2023-10-16

可能重复:
比较std::wstring和std::string

我有个愚蠢的问题。我知道我可以在字符串之前使用L前缀,将其用作wchar_t*(用于unicode字符串(,但我不知道如何在变量之前使用此前缀。我是说

std::wstring str = L"hello";

我知道上面的代码,但这个怎么样:

string somefunction();
std::wstring str1 = L(somfunction()) 

这意味着没有找到"L"标识符

问题是如何将L前缀应用于未引用的字符串?

void wordNet::extractWordIds(wstring targetWord)
{
    pugi::xml_document doc;
    std::ifstream stream("words0.xml");
    pugi::xml_parse_result result = doc.load(stream);
    pugi::xml_node words = doc.child("Words");
    for (pugi::xml_node_iterator it = words.begin(); it != words.end(); ++it)
    {       
        std::string wordValue =  as_utf8(it->child("WORDVALUE").child_value());
        std::wstring result (wordValue.size (), L' ');
        std::copy (wordValue.begin (), wordValue.end (), result.begin ()); 
        if(!result.compare(targetWord))
            cout << "found!" << endl; 
    }

}

实际上,我想比较targetWord和wordValue。您可以看到,我将wordValue转换为wstring,但通过比较仍然没有得到正确的结果。

不能,它是字符串文字本身的一部分。这不是操作员。

string-literal:
    encoding-prefixopt "s-char-sequenceopt"
    encoding-prefixoptR raw-string
encoding-prefix:
    u8
    u
    U
    L

此外,我还建议您避免使用std::wstrings,除非您进行低级别的windows API调用。

编辑:

如果您使用PUGIXML_WCHAR_MODE编译pugixml,请使用:

    if(it->child("WORDVALUE").child_value() == targetWord)
        cout << "found!" << endl; 

否则使用:

    if(it->child("WORDVALUE").child_value() == pugi::as_utf8(targetWord))
        cout << "found!" << endl; 

我建议在不使用PUGIXML_WCHAR_MODE的情况下编译,并将函数更改为:

void wordNet::extractWordIds(std::string targetWord)
{
    // ...
    for (pugi::xml_node_iterator it = words.begin(); it != words.end(); ++it)
        if(it->child("WORDVALUE").child_value() == targetWord)
            cout << "found!" << endl; 
}

并且让调用者担心传递UTF-8 targetWord

您必须使somfunction返回std::wstringwchar_t*

如果您无法更改函数返回类型,则需要从string转换为wstring,这在编译时是无法完成的-您需要调用一个函数才能完成。这个问题已经被问了很多次,有很多不同的变体,下面是一个例子:C++将字符串(或char*(转换为wstring(或wchar_t*(

你不能。

您应该将字符串的结果复制到wstring中,例如:

std::string tmp = somefunction ();
std::wstring result (tmp.size (), L' ');
std::copy (tmp.begin (), tmp.end (), result.begin ());

来自pugixml文档:

在某些情况下,您必须在UTF-8和wchar_t编码之间转换字符串数据;提供以下辅助功能用于此类目的:

std::string as_utf8(const wchar_t* str);
std::wstring as_wide(const char* str);