您的位置:首页 > 其它

VS2008下面控制台下面的宽字符中文输出

2011-12-08 10:50 246 查看
今天碰到一个问题,就是在VS2008下面的控制台程序里面,从一个文本文件里面读取出相应的内容,中文的,然后想到控制台下面显示出来,过程都很顺利,先读取出来放到char* cpContent里面,然后利用MultiByteToWideChar转换成宽字符wchar_t * wpContent,然后利用wprintf进行输出,在调试的时候,可以看到wpContent里面存放的是中文内容,但是输出之后却显示乱码。开始不知道为什么?后来在wprintf输出之前,加了一句代码

setlocale(LC_ALL, "chs");

中文内容立马就输出成功了。

后来仔细看了一下,原来是这个样子的

setlocale:本函数用来配置地域的信息,设置当前程序使用的本地化信息。

当C语言程序初始化时(刚进入到 main() 时),locale 被初始化为默认的 C locale,其采用的字符编码是所有本地 ANSI 字符集编码的公共部分,是用来书写C语言源程序的最小字符集(所以才起locale名叫:C)。

那么就与我们要求输出的不一致了,因此要进行相应的设置setlocale(LC_ALL, "chs");

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

这个函数的参数还有其他的输入,大家可以看一下相关说明。

函数的相关定义如下(下面直接从MSDN拷贝,或者大家可以直接Google搜setlocale):

char *setlocale(
int category,
const char *locale
);
wchar_t *_wsetlocale(
int category,
const wchar_t *locale
);

Parameters

category Category affected by locale. locale Locale name.

Return Value

If a valid locale and category are given, returns a pointer to the string associated with the specified locale and category. If the locale or category is invalid, returns a null pointer and the current locale settings of the program are not changed.

For example, the call

setlocale( LC_ALL, "English" );

sets all categories, returning only the string
English_USA.1252
. If all categories are not explicitly set by a call tosetlocale, the function returns a string indicating the current setting of each of the categories,
separated by semicolons. If thelocale argument is a null pointer,
setlocale
returns a pointer to the string associated with thecategory of the program's locale; the program's current locale setting is not changed.

The null pointer is a special directive that tells setlocale to query rather than set the international environment. For example, the sequence of calls

// Set all categories and return "English_USA.1252"
setlocale( LC_ALL, "English" );
// Set only the LC_MONETARY category and return "French_France.1252"
setlocale( LC_MONETARY, "French" );
setlocale( LC_ALL, NULL );

returns

LC_COLLATE=English_USA.1252;
LC_CTYPE=English_USA.1252;
LC_MONETARY=French_France.1252;
LC_NUMERIC=English_USA.1252;
LC_TIME=English_USA.1252

which is the string associated with the LC_ALL category.

You can use the string pointer returned by setlocale in subsequent calls to restore that part of the program's locale information, assuming that your program does not alter the pointer or the string. Later calls tosetlocale
overwrite the string; you can use
_strdup to save a specific locale string.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: