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; } 
4
  • 1
    Error (active)no instance of overloaded function "swprintf_s" matches the argument list Commented Jan 6, 2016 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. Commented Jan 6, 2016 at 18:47
  • 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. Commented Jan 6, 2016 at 18:50
  • This sounds like an XY problem. What are you actually trying to achieve? Commented Jan 6, 2016 at 19:03

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

"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).
@hvd you are technically correct, but the string.length() will not be updated.
@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
Thanks. you are right. fixed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.