我正在尝试wchar_t
从stdin中获取一个字符串,然后通过一个函数将其从unicode转换为ASCII。
该功能某种程度上不允许我在程序中进一步使用std :: string。
#include <iostream>
#include <string>
#include <locale>
#include <cstring>
#include <cwchar>
using namespace std;
bool UnicodeToAscii(wchar_t* szUnicode, char* szAscii);
int main()
{
wchar_t w[100];
wcin>>w;
char* c;
bool x=UnicodeToAscii(w,c);
cout<<c<<"\n";
string s="hi";
return 0;
}
bool UnicodeToAscii(wchar_t* szUnicode, char* szAscii)
{
int len, i;
if((szUnicode == NULL) || (szAscii == NULL))
return false;
len = wcslen(szUnicode);
for(i=0;i<len+1;i++)
*szAscii++ = static_cast<char>(*szUnicode++);
return true;
}
您没有为分配任何内存c
,因此您正在将字符数据写入随机内存并破坏了程序。
您应该停止使用字符数组和原始指针,而开始使用std::string
和std::wstring
。让他们为您管理内存。
尝试这个:
#include <iostream>
#include <string>
void UnicodeToAscii(const std::wstring &szUnicode, std::string &szAscii);
int main()
{
std::wstring w;
std::wcin >> w; // or std::getline(wcin, w);
std::string c;
bool x = UnicodeToAscii(w, c);
std::cout << c << "\n";
std::string s = "hi";
return 0;
}
void UnicodeToAscii(const std::wstring &szUnicode, std::string &szAscii)
{
szAscii.clear(len);
int len = szUnicode.length();
char c;
szAscii.reserve(len);
for(int i = 0; i < len; ++i)
{
wchar_t w = szUnicode[i];
if ((w >= 0) && (w < 127))
{
// ASCII character
c = static_cast<char>(w);
}
else
{
// non-ASCII character
c = '?';
// wchar_t is 2 bytes (UTF-16) on some systems,
// but is 4 bytes (UTF-32) on other systems...
#if sizeof(wchar_t) == 2
if ((w >= 0xD800) && (w <= 0xDFFF))
{
// skip first unit of a surrogate pair,
// the loop will skip the second unit...
++i;
}
#endif
}
szAscii.push_back(c);
}
return true;
}
当然,这是非常基本的,它只能处理真正的ASCII字符(0x00-0x7F)。正确处理Unicode比这复杂得多。但这回答了您的紧迫问题,即为什么std::string
在调用函数后不能使用-因为这浪费了内存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句