在VC++的世界里,MS比较鼓励使用_UNICODE,std::wstring。VC++默认构造std::string的时候是ANSI格式。
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
#include <fstream>
int main(int argc, char *argv[])
{
std::wstring str = L"123,我是谁?我爱钓鱼岛!";
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
std::string narrowStr = conv.to_bytes(str);
{
std::ofstream ofs("c:\\test.txt");
ofs << narrowStr;
}
std::wstring wideStr = conv.from_bytes(narrowStr);
{
std::locale::global(std::locale("Chinese-simplified"));
std::wofstream ofs(L"c:\\testW.txt");
ofs << wideStr;
}
}
本文介绍在VC++环境下如何使用标准库函数进行Unicode(宽字符)与ANSI(窄字符)字符串的相互转换,通过示例代码演示了std::wstring与std::string之间的转换过程,并展示了如何将转换后的字符串写入文件。
3851

被折叠的 条评论
为什么被折叠?



