Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting std::wsting to char* with wcstombs_s

I have input strings that contain only digits (just the plain Latin ones, 0-9, so for example "0123"), stored as std::wstring, and I need each as a char*. What's the best way for me to do this? This is my initial approach:

void type::convertWStringToCharPtr(_In_ std::wstring input, _Out_ char * outputString)
{
    outputString = new char[outputSize];
    size_t charsConverted = 0;
    const wchar_t * inputW = input.c_str();
    wcstombs_s(&charsConverted, outputString, sizeof(outputString), inputW, input.length());
}

EDIT: The code below works. Thanks all!

void type::convertWStringToCharPtr(_In_ std::wstring input, _Out_ char * outputString)
{
    size_t outputSize = input.length() + 1; // +1 for null terminator
    outputString = new char[outputSize];
    size_t charsConverted = 0;
    const wchar_t * inputW = input.c_str();
    wcstombs_s(&charsConverted, outputString, outputSize, inputW, input.length());
}
like image 987
Justin R. Avatar asked Sep 05 '13 20:09

Justin R.


2 Answers

There are a couple of errors in your code. First, you're not allocating enough space in your destination buffer for the NULL character. You must allocate at least input.length() + 1 chars for the function to succeed.

Second, you're not passing in the correct size of the output buffer to the function. sizeof(outputString) returns the size of outputString itself, a char *, and not the number of bytes pointed to by that pointer.

So your function should look like this:

void CoverageTileManager::convertWStringToCharPtr(_In_ std::wstring input, _Out_ char * outputString)
{
    size_t outputSize = input.length() + 1;
    outputString = new char[outputSize];
    size_t charsConverted = 0;
    wcstombs_s(&charsConverted, outputString, outputSize, input.c_str(), input.length());
    // TODO verify charsConverted = outputSize
}
like image 52
Praetorian Avatar answered Sep 23 '22 11:09

Praetorian


You are not allocating enough memory for your buffer:

char * outputString = new char[input.length()];

Should be

char * outputString = new char[input.length() + 1];

because of terminating NUL-character.

Oh, and also, as per pm100's comment: sizeof(outputString) is giving you the size of the pointer. You should use input.length() + 1, as that is the size of the buffer.

like image 35
Nemanja Boric Avatar answered Sep 22 '22 11:09

Nemanja Boric