C++ 如何在c+中将单字节字符串转换为宽字符串+;?
我知道编码,输入字符串是100%单字节的,没有像utf之类的奇特编码。我只想根据已知编码将其转换为wchar_t*或wstring。使用什么功能<代码>btowc()然后循环?也许字符串对象中有一些有用的东西。有很多例子,但都是针对“多字节”或带有btowc()的奇特循环的,这些循环只显示了如何在屏幕上显示输出,这个函数确实在工作,我还没有看到任何严肃的例子,在这种情况下如何处理缓冲区,总是宽字符比单个字符字符串大2倍?试试这个。这对我很有用 (作者不详)C++ 如何在c+中将单字节字符串转换为宽字符串+;?,c++,string,winapi,widestring,C++,String,Winapi,Widestring,我知道编码,输入字符串是100%单字节的,没有像utf之类的奇特编码。我只想根据已知编码将其转换为wchar_t*或wstring。使用什么功能btowc()然后循环?也许字符串对象中有一些有用的东西。有很多例子,但都是针对“多字节”或带有btowc()的奇特循环的,这些循环只显示了如何在屏幕上显示输出,这个函数确实在工作,我还没有看到任何严肃的例子,在这种情况下如何处理缓冲区,总是宽字符比单个字符字符串大2倍?试试这个。这对我很有用 (作者不详) /*string2wstring.h*/ #布
/*string2wstring.h*/
#布拉格语一次
#包括
#包括
#包括
#包括
#包括
//把这个类放在你的个人工具箱里。。。
模板
类加宽:公共std::一元函数<
常量std::string&,std::basic\u string>
{
std::locale loc;
const std::ctype*pCType\ux;
//没有复制构造函数,没有赋值运算符。。。
加宽(const加宽&);
加宽运算符=(常量加宽&);
公众:
//构造器。。。
加宽(const std::locale&loc=std::locale()):loc(loc)
{
#如果定义(_MSC_VER)&(_MSC_VER<1300)//VC++6.0。。。
使用名称空间std;
pCType=和使用(loc、ctype);
#否则
pCType=&std::使用切面(loc);
#恩迪夫
}
//转换。。。
std::basic_字符串运算符()(const std::string&str)const
{
typename std::基本字符串::大小类型srcLen=
str.length();
const char*pSrcBeg=str.c_str();
std::载体tmp(srcLen);
pCType_u2;->加宽(pSrcBeg、pSrcBeg+srcLen和tmp[0]);
返回std::basic_字符串(&tmp[0],srcLen);
}
};
//如何使用它。。。
int main()
{
加宽至_wstring;
std::string s=“我的测试字符串”;
std::wstring w=至_wstring(s);
STD::好的,什么是编码?你想坚持标准C++吗?我更喜欢坚持标准C++,但是如果它是WiAPI的一种简单的方法,对我来说没问题。第二,编码是代码> Windows 1250版/代码>,但可能是其他的,比如ISO8595-5西里尔。请参见这里的例子:请不要只在某个站点页面上发布链接。请在这里提供内容。我编辑了它,但我也可以提供链接吗?因为我不知道作者,希望显示代码的来源。当然,如果可能,请提供链接并给出适当的属性。
/* string2wstring.h */
#pragma once
#include <string>
#include <vector>
#include <locale>
#include <functional>
#include <iostream>
// Put this class in your personal toolbox...
template<class E,
class T = std::char_traits<E>,
class A = std::allocator<E> >
class Widen : public std::unary_function<
const std::string&, std::basic_string<E, T, A> >
{
std::locale loc_;
const std::ctype<E>* pCType_;
// No copy-constructor, no assignment operator...
Widen(const Widen&);
Widen& operator= (const Widen&);
public:
// Constructor...
Widen(const std::locale& loc = std::locale()) : loc_(loc)
{
#if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6.0...
using namespace std;
pCType_ = &_USE(loc, ctype<E> );
#else
pCType_ = &std::use_facet<std::ctype<E> >(loc);
#endif
}
// Conversion...
std::basic_string<E, T, A> operator() (const std::string& str) const
{
typename std::basic_string<E, T, A>::size_type srcLen =
str.length();
const char* pSrcBeg = str.c_str();
std::vector<E> tmp(srcLen);
pCType_->widen(pSrcBeg, pSrcBeg + srcLen, &tmp[0]);
return std::basic_string<E, T, A>(&tmp[0], srcLen);
}
};
// How to use it...
int main()
{
Widen<wchar_t> to_wstring;
std::string s = "my test string";
std::wstring w = to_wstring(s);
std::wcout << w << L"\n";
}