Search code examples
stringcharc++-cli

In C++/CLI, how to copy a char * to a System::String (not a C++ std::string)?


Though I know C well, I'm having trouble with copying a char array to a System::String (not a C++ std::string) in C++/CLI.

I'm using (for the first time) Visual Studio with its drop-and-drag form design feature to create a C++ Windows GUI program. The program works mostly, but I'm having trouble copying a char array (created with sprintf) to a System::String (the type used by many of the Visual Studio controls).

I tried writing this function:

private: System::String^ cts(char *aa) {  // convert char[] to String

    int i;
    String^ s;

    s = "";
    for (i = 0; aa[i]; i++)
        s = s + aa[i];
    return s;
}

But cts("h") returns "104" (the ASCII code for lower case h), and I want it to return "h" in String format.

Help would be appreciated.


Solution

  • System::String has a constructor that accepts a const char*.
    Therefore all you have to do is to use gcnew to create a new System::String passing the const char* as a parameter (a char* can also be passed).

    See the code below:

    System::String^ cts(const char *aa)
    {
        return gcnew System::String(aa);
    }
    
    int main()
    {
        System::String ^ system_str = cts("abcd");
        System::Console::WriteLine(system_str);
        return 0;
    }
    

    Output:

    abcd