1

私はエンコーディングを知っており、入力文字列は 100% 1 バイトであり、utf などの派手なエンコーディングはありません。必要なのは、既知のエンコーディングに基づいて wchar_t* または wstring に変換することだけです。使用する機能は? btowc()そしてループ?おそらく、文字列オブジェクトには何か便利なものがあります。多くの例がありますが、すべて「マルチバイト」または btowc() を使用した派手なループ用であり、実際にこの関数が機能していることを画面に表示する方法のみを示しています。そのようなバッファを処理する方法の深刻な例は見たことがありません状況では、常にワイド文字は単一の文字列よりも 2 倍大きいですか?

4

1 に答える 1

3

このテンプレートを試してください。とても役に立ちました。

(作者不明)

/* 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";
 }
于 2012-12-15T16:43:47.020 に答える