1

How can i use std::wstring variable as argument in to swprintf_s instead wchar_t *?

My code is as below but has error:

#include <string>
#include <iostream>
using namespace std;

int main(){
    std::wstring     msg(20, 0);
    swprintf_s( msg.c_str(), 20, L"This is a test for using std::wstring");//this line has error

 wcout<< msg<< endl;
return 0;
}
SaeidMo7
  • 1,214
  • 15
  • 22
  • 1
    Error (active)no instance of overloaded function "swprintf_s" matches the argument list – SaeidMo7 Jan 06 '16 at 18:47
  • 1
    You can not do this directly because the underlying buffer isn't meant to be written to. Other fields in the string object don't get correctly updated (like length) even if you force it with creative casting causing weird errors to manifest later. – Donnie Jan 06 '16 at 18:47
  • http://en.cppreference.com/w/cpp/string/basic_string The signature for std::wstring::c_str is "const wchar_t * c_str() const;" that means it returns a "const wchar_t *" while swprintf_s wants a "wchar_t *". So you should look at a different way to do this. – Jason Harrison Jan 06 '16 at 18:50
  • This sounds like an XY problem. What are you actually trying to achieve? – NathanOliver Jan 06 '16 at 19:03

1 Answers1

0

swprintf or swprintf_s writes to the memory pointed by its first parameter. Therefore that parameter cannot be a const char or wchar pointer. But the return value of std::wstring::c_str() is const char* . So you cannot just cast way the const. As mentioned by Jason, if you break the rule, wstring::size() may not return the right value.

What you can do is

wchar_t buffer[20];

swprintf_s(buffer, 20, L"This is a test for using std::wstring");

If you want a std::wstring, you can just use the constructor, like wstring msg(buffer).

CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • "So you cannot just cast way the 'const'." -- You can, as of C++11. `msg.c_str()` is guaranteed to be the same as `&msg[0]` (provided the string is non-empty). –  Jan 06 '16 at 19:01
  • @hvd you are technically correct, but the string.length() will not be updated. – Jason Harrison Jan 06 '16 at 19:02
  • @CS Pei There is a syntax error in your solution. `wchar_t * buffer[20];` should be changed to `wchar_t buffer[20];` as we don't need pointer to array – shan Jan 06 '21 at 07:19
  • Thanks. you are right. fixed – CS Pei Jan 08 '21 at 17:37