这段程序在windows2003 和xp上运行结果,看看有什么不一样
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
void main()
{
string str = "周末 大家 一起 出去玩";
cout << "before erase str:" << str << endl;
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
cout << "after erase sapce:" << str.c_str() << endl;
}
windows 2003结果:
before erase str:周末 大家 一起 出去玩
after erase sapce:周末大家一起出去玩
windows xp在去掉空格后会输出乱码;
我想可能是2003与xp的默认字符集不一样的结果造成的;
修改后再在2003和xp上测试:
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
wstring s2ws(const std::string& s);
string ws2s(const std::wstring& ws);
void main()
{
string str("周末 大家 一起 出去 玩");
wstring wstr = s2ws(str);
cout << "before erase space str:" << str <<endl;
wstr.erase(remove_if(wstr.begin(), wstr.end(), isspace), wstr.end());
str = ws2s(wstr);
cout << "after erase sapce: " << str <<endl;
}
string ws2s(const wstring& ws)
{
string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "chs");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
memset(_Dest,0,_Dsize);
wcstombs(_Dest,_Source,_Dsize);
string result = _Dest;
delete []_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
wstring s2ws(const string& s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
wstring result = _Dest;
delete []_Dest;
setlocale(LC_ALL, "C");
return result;
}
before erase str:周末 大家 一起 出去玩
after erase sapce:周末大家一起出去玩