2016-10-04 83 views
0

我想知道是否有更簡單的方法(更簡練)轉換const char_t*std::string_t而不是下面更好的辦法。到常量爲wchar_t *轉換爲常量的std :: basic_string的<char_t>

編輯

#ifdef OS_WIN 
#include <tchar.h> 
typedef wchar_t char_t; 
#define CHAR_WIDE 
#else 
typedef char char_t; 
+1

'typedef wchar_t char_t;'你確定嗎? – deviantfan

+0

看到編輯請... –

+0

你想做什麼?要將'std :: string'轉換爲'std :: wstring',你應該使用'std :: iconv' – PnotNP

回答

6

從你有typedef S,它歸結要一個wchar_t const*字符串轉換爲std::basic_string<wchar_t>。你可以只通過該wchar_t const*串的範圍分成的std::basic_string<wchar_t>構造:

wchar_t const *str = L"abcdefgh"; 
const std::basic_string<wchar_t> script_name(str, str + std::char_traits<wchar_t>::length(str)); 

Live Demo

3

你有三種常見的情況:

  1. wchar_t*必須指向ASCII值只有,並且您想要ASCII碼爲std::string
  2. wchar_t*可能指向非ASCII字符,你想一個std::string寬字符
  3. wchar_t*可能指向非ASCII字符,你想在UTF-8 std::string

通常情況3是最不可能在程序的其他地方引起問題的最好方式。但它也是最難處理的,因爲您需要提供自己的例程來將寬字符轉換爲UTF-8。網上有很多C++源文件可用於這項工作。

爲1:

std::string answer; 
for(i=0;i<N;i++) 
    answer.push_back((char) wcharptr[i]); 

爲2,同樣的代碼,但是你需要模板回答你想要的寬型,顯然刪除char演員。這就是生活變得困難的原因,爲什麼會不受歡迎,因爲如果不小心的話,最終會出現大量不同類型的std::string

爲3:

std::string answer; 
for(i=0;i<N;i++) 
{ 
    char utf8[8]; 
    int Nutf8; 
    int ii; 

    Nutf8 = widetoutf8(utf8, wcharptr[i]); 
    for(ii=0;ii<Nutf8;ii++) 
     answer.push_back(utf8[ii]);  
} 

,您必須提供widetoutf8()或等同。

相關問題