By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,509 Members | 1,307 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,509 IT Pros & Developers. It's quick & easy.

Convert String to Char*

P: 54
Hey all. I have a small problem. I have a string called hexed. inside hexed for example is the string "003eb". I need to be able to convert this string into a char* because i have a predefined function that converts hexadecimal to decimal but its parameter that needs to be passed to it is a char *. I have been looking into a few things and Im just a little confused on how to implement it.
Apr 14 '09 #1
Share this Question
Share on Google+
5 Replies


Banfa
Expert Mod 5K+
P: 8,964
You can't convert string to char *. You can convert string to const char * using the method string::c_str.

To do what you want you would need to copy the string to an array of char of an appropriate length using strcpy and string::c_str, call your function then assign the result back to your string.

It may be easier or at least produce cleaner code to re-write (or write an overload for) you function that operates directly on a string.
Apr 14 '09 #2

Expert 100+
P: 464
I have used this to assign a CString to a char *.

char* = (char *) (LPCTSTR)CString;

I don't know if that will help you or not.
Apr 17 '09 #3

Banfa
Expert Mod 5K+
P: 8,964
Since the op is planning on writing data to that pointer that would be a really bad idea. You have cast away the constness of a pointer, always a disaster waiting to happen.

However mentioning CString if you happen to be using MFC and CString then you can call the method GetBuffer which returns a char * and allows you to specify the size of the buffer that the returned pointer points to (not forgetting to call ReleaseBuffer once finished)
Apr 17 '09 #4

Expert 100+
P: 464
I didn't see where he stated that he was going to write to it, but yeah is definitely something to look out for and I should have stated that. If the function only reads items in the char* it should work fine, but it isn't safe. Thanks for the tip about the GetBuffer, I'll have to try it out.
Apr 18 '09 #5

weaknessforcats
Expert Mod 5K+
P: 9,197
char* = (char *) (LPCTSTR)CString;
Be careful of this code. CString be either a char* string or a wchar_t* string. And you can't tell which.

Once you start using TCHAR mappings, like LPCTSTR, then you can no longer use the natives types directly. Everything must now be TCHAR.

The char* would become a PTCHAR.
Apr 19 '09 #6

Post your reply

Sign in to post your reply or Sign up for a free account.