使用wcstombs_s()把WCHAR字串转换成char字串,怎么转不了中文?

C语言 码拜 9年前 (2015-05-11) 2498次浏览 0个评论
 

我用msdn的例子来试验:

#include “stdafx.h”

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define BUFFER_SIZE 100

int main( void )
{
    size_t   i;
    char   *  pMBBuffer = (char *)malloc( BUFFER_SIZE );
    wchar_t*  pWCBuffer = L”Hello, world.”;                             //(1)
    //wchar_t*  pWCBuffer = L”世界, 你好.”;  //换成_T(“世界, 你好.”)也不行 //(2)

    printf( “Convert wide-character string:\n” );

    // Conversion
    wcstombs_s(&i, pMBBuffer, (size_t)BUFFER_SIZE, 
               pWCBuffer, (size_t)BUFFER_SIZE );

    // Output
    printf(”   Characters converted: %u\n”, i);
    printf(”    Multibyte character: %s\n\n”,
     pMBBuffer );

    // Free multibyte character buffer
    if (pMBBuffer)
    {
    free(pMBBuffer);
    }
}

msdn的代码肯定是没事的,但我把上面(1)句注释掉换成(2)句,即字串换成中文,就不行了!打印不出来转换后的文字,设断点查pMBBuffer,发现wcstombs_s调用后pMBBuffer是空的,什么都没转出来。

为什么英文可以中文不行?why?

40分
调用wcstombs之前先调setlocale(LC_ALL, “zh-CN”);否则wcstombs不会处理超过255的字符,不过这到底是bug还是标准就不知道了。
原则上应该是setlocale(LC_CTYPE, “zh-CN”);,因为wcstombs用的不是系统code page而是设置LC_CTYPE时候获得的code page,LC_CTYPE默认是空的。
在wcstombs_s()前加了setlocale(LC_ALL, “zh-CN”)或setlocale(LC_CTYPE, “zh-CN”)甚至两句都加也还不行呀。还是转不出中文。
Convert wide-character string:
   Characters converted: 12
    Multibyte character: 世界, 你好.

Press any key to continue . . .

那就不知道是怎么回事鸟…

查了下,我这里要写:
setlocale(LC_ALL,””);
或者
setlocale(LC_ALL, “chs”);

难道不同机器或不同系统有关系?
我的是win7, vs2008

嗯… 貌似直接用locale name是2012才加的。
据说
setlocale(LC_ALL,”chs”);

_wsetlocale(LC_ALL,L”chs”);
不是一回事。
20分
 Collapse AllExpand All      Code: All Code: Multiple Code: Visual Basic Code: C# Code: Visual C++ Code: J# Code: JScript
Visual Basic
C#
Visual C++
J#
JScript
Run-Time Library Reference 
wcstombs_s, _wcstombs_s_l 
Example  See Also  Send Feedback 
 

Converts a sequence of wide characters to a corresponding sequence of multibyte characters. A version of wcstombs, _wcstombs_l with security enhancements as described in Security Enhancements in the CRT.

 
errno_t wcstombs_s(
   size_t *pReturnValue,
   char *mbstr,
   size_t sizeInBytes,
   const wchar_t *wcstr,
   size_t count 
);
errno_t _wcstombs_s_l(
   size_t *pReturnValue,
   char *mbstr,
   size_t sizeInBytes,
   const wchar_t *wcstr,
   size_t count,
   _locale_t locale
);
template <size_t size>
errno_t wcstombs_s(
   size_t *pReturnValue,
   char (&mbstr)[size],
   const wchar_t *wcstr,
   size_t count 
); // C++ only
template <size_t size>
errno_t _wcstombs_s_l(
   size_t *pReturnValue,
   char (&mbstr)[size],
   const wchar_t *wcstr,
   size_t count,
   _locale_t locale
); // C++ only
 

Parameters
[out] pReturnValue
The number of characters converted.

[out] mbstr
The address of a buffer for the resulting converted multibyte character string.

[in]sizeInBytes
The size in bytes of the mbstr buffer.

[in] wcstr
Points to the wide character string to be converted.

[in] count
The maximum number of bytes to be stored in the mbstr buffer, or _TRUNCATE.

[in] locale
The locale to use.

Return Value
Zero if successful, an error code on failure.

Error condition
 Return value and errno
 
mbstr is NULL and sizeInBytes > 0
 EINVAL
 
wcstr is NULL
 EINVAL
 
The destination buffer is too small to contain the converted string (unless count is _TRUNCATE; see Remarks below)
 ERANGE
 

If any of these conditions occurs, the invalid parameter exception is invoked as described in Parameter Validation . If execution is allowed to continue, the function returns an error code and sets errno as indicated in the table.

Remarks
The wcstombs_s function converts a string of wide characters pointed to by wcstr into multibyte characters stored in the buffer pointed to by mbstr. The conversion will continue for each character until one of these conditions is met:

A null wide character is encountered

A wide character that cannot be converted is encountered

The number of bytes stored in the mbstr buffer equals count.

The destination string is always null-terminated (even in the case of an error).

If count is the special value _TRUNCATE, then wcstombs_s converts as much of the string as will fit into the destination buffer, while still leaving room for a null terminator.

If wcstombs_s successfully converts the source string, it puts the size in bytes of the converted string, including the null terminator, into *pReturnValue (provided pReturnValue is not NULL). This occurs even if the mbstr argument is NULL and provides a way to determine the required buffer size. Note that if mbstr is NULL, count is ignored.

If wcstombs_s encounters a wide character it cannot convert to a multibyte character, it puts 0 in *pReturnValue, sets the destination buffer to an empty string, sets errno to EILSEQ, and returns EILSEQ.

If the sequences pointed to by wcstr and mbstr overlap, the behavior of wcstombs_s is undefined.

Security Note: 
Ensure that wcstr and mbstr do not overlap, and that count correctly reflects the number of wide characters to convert.
 

wcstombs_s uses the current locale for any locale-dependent behavior; _wcstombs_s_l is identical to wcstombs except that it uses the locale passed in instead. For more information, see Locale.

In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically (eliminating the need to specify a size argument) and they can automatically replace older, non-secure functions with their newer, secure counterparts. For more information, see Secure Template Overloads.

Requirements
Routine
 Required header
 
wcstombs_s
 <stdlib.h>
 

For additional compatibility information, see Compatibility in the Introduction.

Example
This program illustrates the behavior of the wcstombs_s function.

  Copy Code 
// crt_wcstombs_s.c
// This example converts a wide character
// string to a multibyte character string.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define BUFFER_SIZE 100

int main( void )
{
    size_t   i;
    char      *pMBBuffer = (char *)malloc( BUFFER_SIZE );
    wchar_t*pWCBuffer = L”Hello, world.”;

    printf( “Convert wide-character string:\n” );

    // Conversion
    wcstombs_s(&i, pMBBuffer, (size_t)BUFFER_SIZE, 
               pWCBuffer, (size_t)BUFFER_SIZE );

    // Output
    printf(”   Characters converted: %u\n”, i);
    printf(”    Multibyte character: %s\n\n”,
     pMBBuffer );

    // Free multibyte character buffer
    if (pMBBuffer)
    {
    free(pMBBuffer);
    }
}
 
  Copy Code 
Convert wide-character string:
   Characters converted: 14
    Multibyte character: Hello, world.
 

.NET Framework Equivalent
Not applicable. To call the standard C function, use PInvoke. For more information, see Platform Invoke Examples.

See Also
Concepts
Data Conversion
Locale
_mbclen, mblen, _mblen_l
mbstowcs, _mbstowcs_l
mbtowc, _mbtowc_l
wctomb_s, _wctomb_s_l
WideCharToMultiByte
Send feedback on this topic to Microsoft.

 Collapse AllExpand All      Code: All Code: Multiple Code: Visual Basic Code: C# Code: Visual C++ Code: J# Code: JScript  
Visual Basic
C#
Visual C++
J#
JScript
Run-Time Library Reference 
Locale 
See Also  Send Feedback 
 

The “Locale” refers to the locality (the Country/Region, and language) for which you can customize certain aspects of your program. Some locale-dependent categories include the formatting of dates and the display format for monetary values. For more information, see Locale Categories.

Use the setlocale function to change or query some or all of the current program or thread locale information while using functions without the _l suffix. The functions with the _l suffix will use the locale parameter passed in for their locale information during the execution of that specific function only. To create a locale for use with a function with a _l suffix, use _create_locale. To free this locale, use _free_locale. To get the current locale, use _get_current_locale.

Use _configthreadlocale to control whether each thread has its own locale, or all threads in a program share the same locale. For more information, see Locales and Code Pages.

More secure versions of the functions in the following table are available, indicated by the _s (“secure”) suffix. For more information, see Security Enhancements in the CRT.

Routine
 Use
 setlocale category setting dependence
 
atof, _atof_l, _wtof, _wtof_l
 Convert character to floating-point value
 LC_NUMERIC
 
atoi, _atoi_l, _wtoi, _wtoi_l
 Convert character to integer value
 LC_NUMERIC
 
_atoi64, _atoi64_l, _wtoi64, _wtoi64_l
 Convert character to 64-bit integer value
 LC_NUMERIC
 
atol, _atol_l, _wtol, _wtol_l
 Convert character to long value
 LC_NUMERIC
 
_atodbl, _atodbl_l, _atoldbl, _atoldbl_l, _atoflt _atoflt_l
 Convert character to double-long value
 LC_NUMERIC
 
is Routines
 Test given integer for particular condition.
 LC_CTYPE
 
isleadbyte, _isleadbyte_l
 Test for lead byte
 LC_CTYPE
 
localeconv
 Read appropriate values for formatting numeric quantities
 LC_MONETARY, LC_NUMERIC
 
MB_CUR_MAX
 Maximum length in bytes of any multibyte character in current locale (macro defined in STDLIB.H)
 LC_CTYPE
 
_mbccpy, _mbccpy_l,_mbccpy_s, _mbccpy_s_l
 Copy one multibyte character
 LC_CTYPE
 
_mbclen, mblen, _mblen_l
 Validate and return number of bytes in multibyte character
 LC_CTYPE
 
strlen, strlen_l, wcslen, wcslen_l, _mbslen, _mbslen_l, _mbstrlen, _mbstrlen_l
 For multibyte-character strings: validate each character in string; return string length 
 LC_CTYPE
 
mbstowcs, _mbstowcs_l,mbstowcs_s, _mbstowcs_s_l
 Convert sequence of multibyte characters to corresponding sequence of wide characters
 LC_CTYPE
 
mbtowc, _mbtowc_l
 Convert multibyte character to corresponding wide character
 LC_CTYPE
 
printf functions
 Write formatted output
 LC_NUMERIC (determines radix character output)
 
scanf functions
 Read formatted input
 LC_NUMERIC (determines radix character recognition)
 
setlocale, _wsetlocale
 Select locale for program
 Not applicable
 
strcoll, wcscoll, _mbscoll, _strcoll_l, _wcscoll_l, _mbscoll_l
 Compare characters of two strings
 LC_COLLATE
 
_stricmp, _wcsicmp, _mbsicmp, _stricmp_l, _wcsicmp_l, _mbsicmp_l
 Compare two strings without regard to case
 LC_CTYPE
 
_stricoll, _wcsicoll, _mbsicoll, _stricoll_l, _wcsicoll_l, _mbsicoll_l
 Compare characters of two strings (case insensitive)
 LC_COLLATE
 
_strncoll, _wcsncoll, _mbsncoll, _strncoll_l, _wcsncoll_l, _mbsncoll_l
 Compare first n characters of two strings 
 LC_COLLATE
 
_strnicmp, _wcsnicmp, _mbsnicmp, _strnicmp_l, _wcsnicmp_l, _mbsnicmp_l
 Compare characters of two strings without regard to case.
 LC_CTYPE
 
_strnicoll, _wcsnicoll, _mbsnicoll, _strnicoll_l, _wcsnicoll_l, _mbsnicoll_l
 Compare first n characters of two strings (case insensitive)
 LC_COLLATE
 
strftime, wcsftime, _strftime_l, _wcsftime_l
 Format date and time value according to supplied format argument
 LC_TIME
 
_strlwr, _wcslwr, _mbslwr, _strlwr_l, _wcslwr_l, _mbslwr_l,_strlwr_s, _strlwr_s_l, _mbslwr_s, _mbslwr_s_l, _wcslwr_s, _wcslwr_s_l
 Convert, in place, each uppercase letter in given string to lowercase
 LC_CTYPE
 
strtod, _strtod_l, wcstod, _wcstod_l
 Convert character string to double value
 LC_NUMERIC (determines radix character recognition)
 
strtol, wcstol, _strtol_l, _wcstol_l
 Convert character string to longvalue
 LC_NUMERIC (determines radix character recognition)
 
strtoul, _strtoul_l, wcstoul, _wcstoul_l
 Convert character string to unsigned long value
 LC_NUMERIC (determines radix character recognition)
 
_strupr, _strupr_l, _mbsupr, _mbsupr_l, _wcsupr_l, _wcsupr,_strupr_s, _strupr_s_l, _mbsupr_s, _mbsupr_s_l, _wcsupr_s, _wcsupr_s_l
 Convert, in place, each lowercase letter in string to uppercase
 LC_CTYPE
 
strxfrm, wcsxfrm, _strxfrm_l, _wcsxfrm_l
 Transform string into collated form according to locale
 LC_COLLATE
 
tolower, _tolower, towlower, _tolower_l, _towlower_l,_mbctolower, _mbctolower_l, _mbctoupper, _mbctoupper_l
 Convert given character to corresponding lowercase character
 LC_CTYPE
 
toupper, _toupper, towupper, _toupper_l, _towupper_l,_mbctolower, _mbctolower_l, _mbctoupper, _mbctoupper_l
 Convert given character to corresponding uppercase letter
 LC_CTYPE
 
wcstombs, _wcstombs_l,wcstombs_s, _wcstombs_s_l
 Convert sequence of wide characters to corresponding sequence of multibyte characters
 LC_CTYPE
 
wctomb, _wctomb_l,wctomb_s, _wctomb_s_l
 Convert wide character to corresponding multibyte character
 LC_CTYPE
 
Note: 
For multibyte routines, the multibyte code page must be equivalent to the locale set with setlocale. _setmbcp, with an argument of _MB_CP_LOCALE makes the multibyte code page the same as the setlocale code page.
 

See Also
Concepts
Internationalization
Run-Time Routines by Category
Send feedback on this topic to Microsoft.

#include <locale.h>
.
.
.
setlocale(LC_ALL,”Chinese-simplified”);//在wcstombs_s之前设置
size_t convertNum;
size_t wsize = wcslen((const wchar_t*)wstr);
size_t asize = wsize * 2 + 1;
char* str = (char*)malloc(asize*sizeof(char));
ZeroMemory(str, asize);

宽字符转为多字符:
方法1:
_wsetlocale(LC_ALL, L”zh-CN”); //需要设置区域语言
wcstombs_s(&convertNum, str, asize, (const wchar_t*)wstr, asize); //注意最后一个参数的大小,不是宽字符的长度,而是多字节的长度。
方法2:
WideCharToMultiByte(CP_ACP, NULL, wstr, -1, str, asize, NULL, NULL);

建议不要用setlocal:
①轻易改变环境变量,容易影响其他程序;
②多线程使用时,依然容易引起乱码,加锁也不行,岂能锁住环境?!
③每次转换都调用,效率低下;
setlocale(LC_ALL,”chs”);

win7    VS2010 WORKED!

引用 11 楼 zwmei 的回复:

size_t convertNum;
size_t wsize = wcslen((const wchar_t*)wstr);
size_t asize = wsize * 2 + 1;
char* str = (char*)malloc(asize*sizeof(char));
ZeroMemory(str, asize);

宽字符转为多字符:
方法1:
_wsetlocale(LC_ALL, L”zh-CN”); //需要设置区域语言
wcstombs_s(&convertNum, str, asize, (const wchar_t*)wstr, asize); //注意最后一个参数的大小,不是宽字符的长度,而是多字节的长度。
方法2:
WideCharToMultiByte(CP_ACP, NULL, wstr, -1, str, asize, NULL, NULL);

WideCharToMultiByte方法确实很好用


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明使用wcstombs_s()把WCHAR字串转换成char字串,怎么转不了中文?
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!