Converting Unicode CString to std::string

I’m having the hardest time converting CString’s to std::strings. I have some filename paths that i need converted to strings, and I’m also trying to verify that they converted correctly by printing on the command line by using:

RhinoApp().Print( L"The converted string is %s \n",convertedToString.c_str());

where convertedToString is a std::string.

Can someone help me here? I just want to be able to work with strings instead of CStrings. I am in a unicode environment

Instead of doing this:

std::string name("Joshua Chen");
const char* szName = name.c_str();

You should do this:

std::wstring name(L"Joshua Chen");
const wchar_t* szName = name.c_str();

Additional resources:

Convert std::string to LPCWSTR
How to: Convert Between Various String Types

Also, the Rhino SDK include ON_String (MBCS) and ON_wString (Unicode) string classes that can be very useful.

Maybe if I knew how to use ON_wString’s or CStrings as global variables, i would use them instead of strings. However, I’m not sure what library to include in order to user CStrings or ON_wStrings. Essentially, I have some extern string variables because I need access to them accross several functions/classes. I dont know how to define these extern variables as ON_wStrings or CStrings without causing errors since I don’t have the necessary libraries included in that header file. Much of this is because I’m not an expert programmer. Would be great if you gave me some pointers here. If I could just work with CStrings or ON_wStrings, that would be easier.

I found out that I can convert a simple CString to string but not a file path.

For example,

CString str(L"Testing");

but not

CString str(L"\\psf\Home\Desktop\Rhino 5 Files\asdfasdfasdfasdfasdf.iga")

or

CString str(L"\\\psf\\Home\\Desktop\\Rhino 5 Files\\asdfasdfasdfasdfasdf.iga")

This is my problem. Neither of these two can be converted to strings…

This will work:

CRhinoCommand::result CCommandTest::RunCommand(const CRhinoCommandContext& context)
{
  CString str(L"\\psf\\Home\\Desktop\\Rhino 5 Files\\asdfasdfasdfasdfasdf.iga");
  const wchar_t* psz = str;
  RhinoApp().Print(L"%s\n", psz);
  return CRhinoCommand::success;
}

To learn more about strings, you might review the following articles, as they will be well worth your time:

The Complete Guide to C++ Strings, Part I
The Complete Guide to C++ Strings, Part II

Also, ON_wString (and ON_String) are very similar to CString and are preferred (for Rhino plug-ins).

You want to convert unicode CString to non-unicode std::string is this right ?
If this is your question then i suggest something like:

std::string tools_wtoa(const wchar_t* in_w)
{
std::wstring w1 = in_w;
std::string out_a;
out_a.assign(w1.begin(), w1.end());
return out_a;
}

Example call:

CString myPath(L"C:\folder\folder\folder\file.jpg");
std::string myConvertedPath = tools_wtoa(myPath);

Not the most scientific way but should be correct.