use*_*824 1 c++ string wstring
我是C++的新手,我遇到了这个问题.我有一个名为DATA_DIR的字符串,我需要将格式化为wstring.
string str = DATA_DIR;
std::wstring temp(L"%s",str);
Run Code Online (Sandbox Code Playgroud)
Visual Studio告诉我没有与参数列表匹配的构造函数实例.显然,我做错了什么.
我在网上找到了这个例子
std::wstring someText( L"hello world!" );
Run Code Online (Sandbox Code Playgroud)
这显然有效(没有编译错误).我的问题是,如何将存储在DATA_DIR中的字符串值放入wstring构造函数中,而不是像"hello world"这样的任意内容?
这是一个使用wcstombs(更新)的实现:
Run Code Online (Sandbox Code Playgroud)#include <iostream> #include <cstdlib> #include <string> std::string wstring_from_bytes(std::wstring const& wstr) { std::size_t size = sizeof(wstr.c_str()); char *str = new char[size]; std::string temp; std::wcstombs(str, wstr.c_str(), size); temp = str; delete[] str; return temp; } int main() { std::wstring wstr = L"abcd"; std::string str = wstring_from_bytes(wstr); }
这是参考投票最多的答案,但我没有足够的“声誉”来直接评论答案。
解决方案“wstring_from_bytes”中的函数名称暗示它正在做原始发布者想要的,即获取给定字符串的 wstring,但该函数实际上与原始发布者要求的相反,并且会更准确被命名为“bytes_from_wstring”。
要将字符串转换为 wstring,wstring_from_bytes 函数应使用 mbstowcs 而不是 wcstombs
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdlib>
#include <string>
std::wstring wstring_from_bytes(std::string const& str)
{
size_t requiredSize = 0;
std::wstring answer;
wchar_t *pWTempString = NULL;
/*
* Call the conversion function without the output buffer to get the required size
* - Add one to leave room for the NULL terminator
*/
requiredSize = mbstowcs(NULL, str.c_str(), 0) + 1;
/* Allocate the output string (Add one to leave room for the NULL terminator) */
pWTempString = (wchar_t *)malloc( requiredSize * sizeof( wchar_t ));
if (pWTempString == NULL)
{
printf("Memory allocation failure.\n");
}
else
{
// Call the conversion function with the output buffer
size_t size = mbstowcs( pWTempString, str.c_str(), requiredSize);
if (size == (size_t) (-1))
{
printf("Couldn't convert string\n");
}
else
{
answer = pWTempString;
}
}
if (pWTempString != NULL)
{
delete[] pWTempString;
}
return answer;
}
int main()
{
std::string str = "abcd";
std::wstring wstr = wstring_from_bytes(str);
}
Run Code Online (Sandbox Code Playgroud)
无论如何,这在标准库的较新版本(C++ 11 和更新版本)中更容易完成
#include <locale>
#include <codecvt>
#include <string>
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(narrow_utf8_source_string);
Run Code Online (Sandbox Code Playgroud)