how to convert wstring to string

来源:互联网 发布:php将数组转化成json 编辑:程序博客网 时间:2024/05/18 00:35

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <locale>#include <codecvt>#include <fstream>#include <sstream>#include <afxwin.h>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 <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;   }}

UTF8文件读取

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <locale>#include <codecvt>#include <fstream>#include <sstream>#include <afxwin.h>using namespace std;int main(){auto LocUtf8 = locale(locale(""),new codecvt_utf8<wchar_t>);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":""}

http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=58.57.91.184

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

zhaoshizhong1老师的方法:

#include <cstdio>#include <locale>#include <iostream>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:[山东]//




原创粉丝点击