博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
how to convert wstring to string
阅读量:3527 次
发布时间:2019-05-20

本文共 2093 字,大约阅读时间需要 6 分钟。

#define _CRT_SECURE_NO_WARNINGS#include 
#include
#include
#include
#include
#include
#include
using namespace std;int main(){ setlocale(LC_CTYPE, "chs"); string str; wstring wstr = L"123呵呵呵abc"; char cstr[100] = {0}; sprintf(cstr, "%S", wstr.c_str()); str = cstr; cout << str << endl;}
写入文件

#include 
#include
#include
#include
#include
int main(int argc, char *argv[]){ std::wstring str = L"123,我是谁?我爱钓鱼岛!"; std::wstring_convert
> 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; }}
UTF8文件读取

#define _CRT_SECURE_NO_WARNINGS#include 
#include
#include
#include
#include
#include
#include
using namespace std;int main(){ auto LocUtf8 = locale(locale(""),new codecvt_utf8
); wifstream wfin("test.txt"); wfin.imbue(LocUtf8); wstring wstr; while (getline(wfin, wstr)) { wcout.imbue(locale("")); wcout << wstr << endl; } wfin.close();}

假如我们取到 的数据是这样的:

{"ret":1,"start":"58.57.64.0","end":"58.57.95.255","country":"\u4e2d\u56fd","province":"\u5c71\u4e1c","city":"\u6f4d\u574a","district":"","isp":"\u7535\u4fe1","type":"","desc":""}

那么我们改怎么样进行转化呢?

zhaoshizhong1老师的方法:

#include 
#include
#include
using namespace std;#define MAXL 100char u[]="\\u4e2d\\u56fd", *p;wchar_t us[MAXL];char str[MAXL];int i;int main(){ setlocale(LC_ALL, "chs"); //_wsetlocale(LC_ALL, L"chs"); //std::locale loc = (std::locale("Chinese-simplified")); i = 0; p = u; while (true) { if (1 != sscanf(p, "\\u%4hx", &us[i])) break; i++; if (i >= MAXL - 1) break; p += 6; } us[i] = 0; //wcout.imbue(loc); sprintf(str, "%S", us); //wcout << us << endl; cout << str << endl; return 0;}//u:[\u5c71\u4e1c]//us:[山东]//

转载地址:http://tffhj.baihongyu.com/

你可能感兴趣的文章