Converting 'TChar' to 'String' in C++

Started by
5 comments, last by bharath 17 years, 4 months ago
Hi Can anybody help me out in this? I need to convert a 'TChar*' to String. Please help me out. Bharath
Advertisement
TCHAR is just a typedef that depending on your compilation configuration (whether you have #define'd UNICODE or not) defaults to char or wchar. Note that you don't necessarily need to #define UNICODE as part of your code. You may also pass it to your target compiler via some preprocessor definition argument, such as /D in microsoft's visual C++ compiler.

Standard Template Library on the other hand supports both ASCII (with std::string) and wide character sets (with std::wstring). All you need to do is to typedef String as either std::string or std::wstring depending on your compilation configuration, if flexibility is what you're aiming for. Something like this might prove useful:

#ifndef UNICODEtypedef std::string String #elsetypedef std::wstring String #endif


Now you may use String in your code and let the compiler handle the nasty parts. String now has constructors that lets you convert TCHAR to std::string or std::wstring.

/EDIT: typo

[Edited by - Ashkan on November 27, 2006 1:59:38 PM]
What exactly are TChar and String? There's Win32 TCHAR which is either a char (ASCII) or wchar (Unicode) and there's std::string. There's also .Net's String (capitalised) which is different from other string types. Assuming you're not using .Net / managed code then the following is what you're after:
TCHAR *tchar_string = "a string";std:string string_string (tchar_string);

but that only works in an ASCII version (TCHAR == char), to use unicode (TCHAR == wchar):
TCHAR *tchar_string = "a string";std:wstring string_string (tchar_string);


Skizz
Quote:Original post by Ashkan
#ifndef UNICODE
typedef std::string String
#else
typedef std::wstring String
#endif
TCHAR already resolves to the correct type, why not use it?
typedef std::basic_string <TCHAR> StringType;

[Edited by - raz0r on November 27, 2006 9:36:33 AM]
Hi

I am using .NET editor for the C++ coding.

Hope i may get some more solutions for the problem I posted
Quote:
I am using .NET editor for the C++ coding.


What do you mean by that? The compiler, the editor and the choice of IDE in general, has no effect on the language itself. If you're writing C++ code, the solutions are already posted.
Hi,

thanks for all who posted a solution for the problem. I followed your ideas and they were working fine.

Thanks again.

This topic is closed to new replies.

Advertisement