之前看网上那些string和wstring的转换一般都要用到<codecvt>库
这段时间在写一个项目时发现其实还有另一个方法,感觉还更简单。
这要用<filesystem>库,里面有个path类,它有个string()方法和wstring()方法用来将path类的内容转为string和wstring类型。具体操作方法如下
#include <filesystem>
#include <string>
using namespace std;
using namespace std::filesystem;
int main() {
// string 转 wstring
string s1 = "hello world"; // 假设这是我有的string
wstring w1 = path(s1).wstring(); // 把他转为wstring
// wstring 转 string
wstring w2 = L"hellp world"; // 假设这是我有的wstring
string s2 = path(w2).string(); // 把他转为string
// 窄字符做参数 转 宽字符
const wchar_t* w3 = path("hello world").wstring().c_str();
// 宽字符做参数 转 窄字符
const char* s3 = path(L"hello world").string().c_str();
return 0;
}
一步到位。