2014-10-01 33 views
0

我有一個程序,要求一個人有他們想要翻譯成Al Bhed的文本,這只是一個密碼,字母在四處移動,並讓SAPI說出來。字符串轉換很好,但這段代碼:讓Sapi說一個字符串

hr = pVoice->Speak(sTranslated, 0, NULL); 

將無法​​正常工作,因爲它說:「從‘的std :: string’到‘常量WCHAR *’沒有合適的轉換函數存在 我要的是對於聲音說翻譯的字符串。我怎麼去呢?

回答

1

首先,你需要的std::string內容,其中使用類型char,爲std::wstring,它使用類型wchar_t轉換,這是由於這樣的事實: ISpVoice::Speak()函數要求第一個參數的類型爲LPCWSTR,IOW指向一個寬字符的const指針ter字符串「。以下功能可能對您有所幫助。

inline std::wstring s2w(const std::string &s, const std::locale &loc = std::locale()) 
{ 
    typedef std::ctype<wchar_t> wchar_facet; 
    std::wstring return_value; 
    if (s.empty()) 
    { 
     return return_value; 
    } 
    if (std::has_facet<wchar_facet>(loc)) 
    { 
     std::vector<wchar_t> to(s.size() + 2, 0); 
     std::vector<wchar_t>::pointer toPtr = &to[0]; 
     const wchar_facet &facet = std::use_facet<wchar_facet>(loc); 
     if (0 != facet.widen(s.c_str(), s.c_str() + s.size(), toPtr)) 
     { 
      return_value = to.data(); 
     } 
    } 
    return return_value; 
} 

然後將代碼行更改爲以下內容。

hr = pVoice->Speak(s2w(sTranslated).c_str(), 0, NULL); 

c_str()方法返回一個指向所述std::wstring對象的「C-等效字符串」。 IOW,它返回一個指向空終止寬字符串的指針。

+0

感謝編輯Remy Lebeau。你顯着改善了我的答案。 – 2014-10-01 02:31:06