user1690531
user1690531

Reputation: 241

Convert a unicode string to a string

I have created some C++ classes in C++ Builder. I am now using these in a VCL forms application. I have a function that loads a text file and takes a string as an argument.

I am using an openDialog control to browse to the file to then open it up.

My problem is this: The .filename property of the openFialog is in the form of UnicodeString and my function needs a std::string. How can I convert a unicode string to a std::string?

Here is my code:

OpenDialog1->Execute();
calCalendar.loadAppointmentsFromFile(OpenDialog1->FileName.t_str());

Here is the function definition:

void loadAppointmentsFromFile(const std::string& stringFilename);

I am getting the following error:

[BCC32 Error] Assessment2.cpp(39): E2342 Type mismatch in parameter 'stringFilename' (wanted 'const std::string &', got 'wchar_t *')

Can I please have some help to rectify this problem?

Upvotes: 2

Views: 8879

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

Use UnicodeString::t_str to get a narrowed string. However, you should consider not mixing the two.

Another option is to convert to an AnsiString first:

AnsiString str = OpenDialog1->FileName;
std::string s(str.c_str());
loadAppointmentsFromFile(s);

Or

std::string s = OpenDialog1->FileName.t_str(); // TCHAR mapping set to char
loadAppointmentsFromFile(s);

Upvotes: 1

Related Questions