2011-06-09 35 views
21

如何将TCHAR数组转换为std::string(不std::basic_string)?如何将TCHAR数组转换为std :: string?

+11

你意识到的std :: string仅仅是一个std一个typedef :: basic_string ? – 2011-06-09 10:37:52

+0

你是否想要将一个特定的Unicode或MBCS TCHAR(即真正的WCHAR或CHAR)总是转换为std :: string(即char),或者将CHAR转换为字符串并将WCHAR转换为wstring或其他东西? – Rup 2011-06-09 10:39:12

回答

29

TCHAR只是一个typedef,根据您的编译配置,默认为charwchar

标准模板库支持ASCII(使用std::string)和宽字符集(使用std::wstring)。所有你需要做的是typedef字符串作为std :: string或std :: wstring,具体取决于你的编译配置。为了保持灵活性,你可以使用下面的代码:

#ifndef UNICODE 
    typedef std::string String; 
#else 
    typedef std::wstring String; 
#endif 

现在你可以在你的代码中使用String,让编译器处理讨厌的部分。字符串现在将具有构造函数,可让您将TCHAR转换为std::stringstd::wstring

+3

问题是我必须调用接受std :: string的接口,所以我不能发送std :: wstring :( – ashmish2 2011-06-09 10:41:31

+0

请参阅[这个问题](http://stackoverflow.com/questions/4804298/c-how-to-对于如何从wstring的字符串转换转换 - wstring的-到串/ 4804506#4804506) – kbjorklu 2011-06-09 10:55:32

+0

如何'String'用'cout'在Unicode的环境中工作 – 2013-07-03 20:43:18

5

TCHAR类型是charwchar_t,具体取决于您的项目设置。

#ifdef UNICODE 
    // TCHAR type is wchar_t 
#else 
    // TCHAR type is char 
#endif 

所以,如果你必须使用std::string代替std::wstring,你应该使用一个转换功能。我可能会使用wcstombsWideCharToMultiByte

TCHAR * text; 

#ifdef UNICODE 
    /*/ 
    // Simple C 
    const size_t size = (wcslen(text) + 1) * sizeof(wchar_t); 
    wcstombs(&buffer[0], text, size); 
    std::vector<char> buffer(size); 
    /*/ 
    // Windows API (I would use this) 
    std::vector<char> buffer; 
    int size = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL); 
    if (size > 0) { 
     buffer.resize(size); 
     WideCharToMultiByte(CP_UTF8, 0, text, -1, static_cast<BYTE*>(&buffer[0]), buffer.size(), NULL, NULL); 
    } 
    else { 
     // Error handling 
    } 
    //*/ 
    std::string string(&buffer[0]); 
#else 
    std::string string(text); 
#endif 
+0

我试过了,得到了:错误C2664:'std :: basic_string <_Elem,_Traits,_Ax> :: basic_string(const std :: basic_string <_Elem,_Traits,_Ax>&)':无法将参数1从'TCHAR [ 50]'const const std :: basic_string <_Elem,_Traits,_Ax>&' – 2013-01-04 01:23:06

+1

@ user396483:我刚刚在VS2012中试过了。代码:[link](http://store.naszta.hu/main/example01.cpp)。 – Naszta 2013-01-04 21:34:22

3

TCHAR或者是char或wchar_t的,所以

typedef basic_string<TCHAR> tstring; 

是这样做的一种方式。

另一种是完全跳过char,只是使用std::wstring

2

我的回答是晚了,我承认,但“阿洛克保存”和一些研究的答案,我已经找到了一个好办法! (注:我没有测试这个版本很多,所以我测试了它应该它可能不会在任何情况下工作,但是从):

TCHAR t = SomeFunctionReturningTCHAR(); 
std::string str; 

#ifndef UNICODE 
    str = t; 
#else 
    std::wstring wStr = t; 
    str = std::string(wStr.begin(), wStr.end()); 
#endif 

std::cout << str << std::endl; //<-- should work! 
+0

它仅适用于7位ASCII码,但会打印其他字符的垃圾。 – palota 2016-02-11 10:35:38

相关问题