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.
Convert String to Char*
Collapse
X
-
Tags: None
-
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. -
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)Comment
-
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.Comment
-
Be careful of this code. CString be either a char* string or a wchar_t* string. And you can't tell which.Originally posted by Studlyamichar* = (char *) (LPCTSTR)CStrin g;
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.Comment
Comment