如何使用L前缀作为未加引号的字符串
how can I use L prefix to unquoted string?
可能重复:
比较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::wstring
或wchar_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);
- 替换字符串中的单词,但忽略引号中的单词
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 从双引号括起来的子字符串中删除特定字符
- 反斜杠和引号不计入字符串长度?
- 如何从路径字符串加载Gdiplus::位图
- 如何将字符串加载到BYTE*数组(C++)的元素中
- 尝试使用 MSMXL 在 c++ 中加载带有 pXMLDom 的字符串
- 使用带有 std::cout 的单引号打印字符串实际上打印了数字
- 匹配外部单引号之间的字符串
- 在字符串流的 SSH 命令中转义 bash 脚本中的引号
- 从中加载字符串时出现 sscanf 问题
- 在类名之后但在中括号之前加引号
- 在 C# 中将单引号字符串到 uint
- TinyXML 从文件加载字符串
- 解析jsoncpp中嵌套转义序列的带引号字符串
- 从文本文件加载字符串后,不会对其进行相应的格式化
- 从输入中加载字符串时的奇怪行为
- 如何使用L前缀作为未加引号的字符串
- C++/SDL从lua加载字符串数组
- getline用于逗号分隔的表文件,在某些字段周围加引号