I know the encoding and that the input string is 100% single byte, no fancy encodings like utf etc. And all I want is to convert it to wchar_t* or wstring basing on a known encoding. What functions to use ? btowc() and then loop ? Maybe string objects have something useful in them. There are lot of examples but all are for "multibyte" or fancy loops with btowc() that only show how to display output on screen that indeed this function is working, I haven't seen any serious example how to deal with buffers in such situation, is always wide char 2x larger than single char string ?

有帮助吗?

解决方案

Try this template. It served me very well.

(author unknown)

/* 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";
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top