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 ?
Asked
Active
Viewed 1,252 times
1

rsk82
- 28,217
- 50
- 150
- 240
-
1Well, what encoding is it? And do you want to stick to standard C++? – David Heffernan Dec 15 '12 at 14:21
-
I prefer to stick to standard c++ but if it is an easy way of doing it by winapi - no problem for me. Second, the encoding is `windows-1250` but may be others like ISO 8859-5 Cyrillic. – rsk82 Dec 15 '12 at 14:23
-
1See the example here: http://en.cppreference.com/w/cpp/string/multibyte/mbstowcs – David Heffernan Dec 15 '12 at 14:29
1 Answers
3
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";
}

marscode
- 373
- 1
- 4
- 10
-
Please don't just post a link to some offsite page. Please provide content here. – David Heffernan Dec 15 '12 at 16:56
-
I edited it, but can I provide the link too? It's because I don't know the author and want to show where the code comes from. – marscode Dec 15 '12 at 17:46
-
1Certainly provide the link and give proper attribution if possible. – David Heffernan Dec 15 '12 at 17:47