c++ - 了解将使用哪个 swprintf(或者再次将 char* 字符串转换为 wchar_t*)

标签 c++ c windows unix mingw

我正在尝试将 char* 字符串转换为 wchar_t*。我看到这个问题已经被问了很多次,但没有解决/可移植的答案/解决方案。

按照建议here , swprintf 对我来说似乎是正确的解决方案,但我发现那里存在两个版本!!即:

  1. http://www.cplusplus.com/reference/cwchar/swprintf/ (第二个参数是字符串容量)
  2. http://msdn.microsoft.com/en-us/library/ybk95axf%28v=vs.71%29.aspx (第二个参数已经是格式字符串)

我的程序看起来像这样:

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

此时:

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

或:

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

并且切换编译器(mingw 4.5.2 <-> mingw 4.7.2)我确实得到了不同版本的实现,所以在一种情况下编译时出错! 我的问题:

  1. 有没有办法知道我必须在编译时选择 2 个接口(interface)中的哪一个?
  2. 是否有替代的、可移植的方法来将 char* 字符串转换为 wchar_t*?例如,如果需要,我可以通过 C++ std 库(无 C++11)

编辑

std::wstring_convert我的编译器似乎不可用(4.5.2 和 4.7.2 都不可用,包括 #include <locale>

我稍后会检查是否可以使用 Boost 格式库来尝试解决这个问题......

最佳答案

既然我会用C++,效率不是问题,我可以用下面的:

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

如果有必要放入一个wchar_t*,它可能是这样的:

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


已测试 here .

文档来自 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.

关于c++ - 了解将使用哪个 swprintf(或者再次将 char* 字符串转换为 wchar_t*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17716763/

相关文章:

c++ - 特征的新手问题

c++ - 除了使用 App Wizard 创建 MFC 应用程序之外,如何获得 MFC 支持?

c - 使用一些 posix 命令的 C 程序

c++ - 编辑 ListView 控件项

c - 如何在清除标准输入之前检查标准输入是否为空

c++ - 定期调用的 c++ 函数

CC\GCC 编译后的可执行文件无法在我的机器上运行?

c - 如何将字符串划分为子字符串并分配另一个子字符串?

windows - Redis 的大文件不会删除?

c++ - 使用指向函数的指针数组创建结构