2012-12-15 94 views
0

我知道編碼和輸入字符串是100%單字節,沒有像UTF等奇特的編碼。我想要的是將其轉換爲基於已知編碼的wchar_t *或wstring。使用哪些功能? btowc()然後循環?也許字符串對象有一些有用的東西。有很多的例子,但都是「多字節」或花式循環與btowc(),只顯示如何顯示輸出在屏幕上,這個功能的工作,我還沒有看到任何嚴肅的例子如何處理這樣的緩衝區情況,總是寬字符2x大於單個字符串?如何將單字節字符串轉換爲C++中的寬字符串?

+1

那麼,什麼編碼呢?你想堅持標準的C++嗎? –

+0

我寧願堅持使用標準的C++,但如果它是通過winapi實現的簡單方法 - 對我來說沒有任何問題。其次,編碼是'windows-1250',但也可能是ISO 8859-5西里爾字符。 – rsk82

+1

請參閱此處的示例:http://en.cppreference.com/w/cpp/string/multibyte/mbstowcs –

回答

2

試試這個template。它非常好。

(作者不詳)

/* 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"; 
} 
+0

請不要只發布鏈接到某個異地頁面。請在此提供內容。 –

+0

我編輯它,但我也可以提供鏈接嗎?這是因爲我不認識作者,並且想要顯示代碼來自哪裏。 – marscode

+1

如果可能,請提供鏈接並提供適當的歸屬。 –