2013-07-18 31 views
1

我想將char *字符串轉換爲wchar_t *。我已經看到這個問題已被多次詢問,沒有解決方案/便攜式答案/解決方案。瞭解將使用哪種swprintf(或再次將char *字符串轉換爲wchar_t *)

正如建議here,swprintf似乎是對我的正確的解決方案,但我發現那裏有兩個版本!即:

  1. http://www.cplusplus.com/reference/cwchar/swprintf/(第二個參數是字符串容量)
  2. http://msdn.microsoft.com/en-us/library/ybk95axf%28v=vs.71%29.aspx(第二個參數是已經格式化字符串)

我的計劃是這樣的:

const unsigned int LOCAL_SIZE = 256; 
char* myCharString = "Hello world!"; 
wchar_t myWCharString[LOCAL_SIZE]; 

在這一點上:

swprintf(myWCharString,LOCAL_SIZE,L"%hs",myCharString); 

或:

swprintf(myWCharString,L"%hs",myCharString); 

和開關編譯器(MinGW的4.5.2 < - > MinGW的4.7.2),我在一種情況下,在編譯時錯誤沒有得到不同版本的順利實施,使! 我的問題:

  1. 有沒有辦法知道我在編譯時需要選擇2個接口中的哪一個?
  2. 是否有替代方案,portable如何轉換wchar_t *中的char *字符串?如果必要的話

我可以通過C++的std庫(沒有C++ 11),例如編輯

std::wstring_convert似乎並不能夠支持我的編譯器(既不4.5.2也不4.7。 2,包括#include <locale>

稍後我會看看我是否可以使用升壓格式庫來嘗試解決這個...

+1

對面沒有來['標準:: wstring_convert'(http://en.cppreference.com/w/cpp/locale/wstring_convert)? – chris

+1

@chris我第一次碰到這個問題,並且在我的許多搜索中找不到任何東西!你可以把它放在答案? – Antonio

+0

'wchar_t * myWCharString [LOCAL_SIZE];'是錯的,應該是'wchar_t myWCharString [LOCAL_SIZE];'。'swprintf(errorWString,LOCAL_SIZE,L「%hs」,errorString);'同樣錯誤,應該是'swprintf(errorWString,sizeof errorWstring,L「%hs」,errorString);'(注意空格和「 sizeof'!) – 2013-07-18 07:11:07

回答

2

因爲我可以使用C++和效率是不是一個問題,我可以使用以下:

std::wstring(myCharString,myCharString+strlen(myCharString)).c_str() 

如果投入wchar_t*是必要的,它可能是這樣的:

strcpy(myWCharString,std::wstring(myCharString,myCharString+strlen(myCharString)).c_str()); 


測試here。從basic_string constructor methods

文檔:

first, last 
    Input iterators to the initial and final positions in a range. 
    The range used is [first,last), which includes all the characters 
    between first and last, including the character pointed by first but not 
    the character pointed by last. 
    The function template argument InputIterator shall be an input iterator type 
    that points to elements of a type convertible to charT. 
    If InputIterator is an integral type, the arguments are casted to the 
    proper types so that signature (5) is used instead.