Understanding which swprintf will be used (or again, convert a char* string to wchar_t*)

泄露秘密 提交于 2020-01-15 09:14:34

问题


I am trying to convert a char* string to wchar_t*. I have seen this question has been asked many times, with no resolving/portable answer/solution.

As suggested here, swprintf seemed the right solution to me, but I found out there exist two versions out there!! Namely:

  1. http://www.cplusplus.com/reference/cwchar/swprintf/ (second argument is the string capacity)
  2. http://msdn.microsoft.com/en-us/library/ybk95axf%28v=vs.71%29.aspx (second argument is already the format string)

My program would look like this:

const unsigned int LOCAL_SIZE = 256;
char* myCharString = "Hello world!";
wchar_t myWCharString[LOCAL_SIZE];

And at this point:

swprintf(myWCharString,LOCAL_SIZE,L"%hs",myCharString );

or:

swprintf(myWCharString,L"%hs",myCharString );

And switching compiler (mingw 4.5.2 <-> mingw 4.7.2) I did get that different version were implemented, so in one case an error at compilation time! My questions:

  1. Is there a way to know which of the 2 interfaces I have to choose at compile time?
  2. Is there an alternative, portable way to transform a char* string in a wchar_t*? I can pass through C++ std libraries (no C++11) for example if necessary

Edit

std::wstring_convert doesn't seem to be available for my compiler (neither 4.5.2 nor 4.7.2, including #include <locale>

I will check out later if I can use Boost Format Library to try to solve this...


回答1:


Since I can use C++, and efficiency is not an issue, I can use the following:

std::wstring(myCharString,myCharString+strlen(myCharString)).c_str()

And if putting in a wchar_t* was necessary, it could be like this:

strcpy(myWCharString,std::wstring(myCharString,myCharString+strlen(myCharString)).c_str() );


Tested here.

Documentation from basic_string constructor methods:

first, last
    Input iterators to the initial and final positions in a range. 
    The range used is [first,last), which includes all the characters
    between first and last, including the character pointed by first but not
    the character pointed by last.
    The function template argument InputIterator shall be an input iterator type
    that points to elements of a type convertible to charT.
    If InputIterator is an integral type, the arguments are casted to the
    proper types so that signature (5) is used instead.


来源:https://stackoverflow.com/questions/17716763/understanding-which-swprintf-will-be-used-or-again-convert-a-char-string-to-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!