Convert String to Char*

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yeshello54
    New Member
    • Mar 2009
    • 54

    Convert String to Char*

    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.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • Studlyami
      Recognized Expert Contributor
      • Sep 2007
      • 464

      #3
      I have used this to assign a CString to a char *.

      char* = (char *) (LPCTSTR)CStrin g;

      I don't know if that will help you or not.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        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

        • Studlyami
          Recognized Expert Contributor
          • Sep 2007
          • 464

          #5
          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

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Originally posted by Studlyami
            char* = (char *) (LPCTSTR)CStrin g;
            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.

            Comment

            Working...