简体   繁体   中英

C++ / Concatenate std::string and wchar* to wchar*

I want to concatenate a std::string and WCHAR* and the result should be in WCHAR* .

I tried the following code

size_t needed = ::mbstowcs(NULL,&input[0],input.length());
std::wstring output;
output.resize(needed);
::mbstowcs(&output[0],&input[0],input.length());
const wchar_t wchar1 = output.c_str();
const wchar_t * ptr=wcsncat( wchar1, L" program", 3 );

I got following errors

error C2220: warning treated as error - no 'object' file generated

error C2664: 'wcsncat' : cannot convert parameter 1 from 'const wchar_t *' to 'wchar_t*'

If you call string.c_str() to get at the raw buffer, it will return a const pointer to indicate that you shouldn't try to change the buffer. And definitely you shouldn't try to concatenate anything to it. Use a second string class instance and let the runtime do most of the work for you.

std::string input; // initialized elsewhere
std::wstring output;

output = std::wstring(input.begin(), input.end());
output = output + std::wstring(L" program"); // or output += L" program";
const wchar_t *ptr = output.c_str();

Also remember this. Once "output" goes out of scope and destructs, "ptr" will be invalid.

As the documentation says

wchar_t * wcsncat ( wchar_t * destination, wchar_t * source, size_t num ); Appends the first num wide characters of source to destination, plus a terminating null wide character. destination is returned. (Source: http://www.cplusplus.com/reference/cwchar/wcsncat/ )

You cannot pass your const wchar1 as destination, because the function will modifiy this and then return it. So you better

  • allocate a wchar array of the appropriate size
  • copy your string into it
  • call wcsncat with your newley allocated wchar array as destination.

However, I wonder if you cannot just use string to do your operations, which is more the C++ way to do it. (Arrays are C-style)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM