Sign in to follow this  
bharath

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

Recommended Posts

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 UNICODE
typedef std::string String
#else
typedef 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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this