wprintf不打印特殊字符

时间:2014-08-06 00:05:56

标签: c++ visual-studio-2013 console-application

我正在尝试使用以下代码打印用于执行程序的参数:

#include "stdafx.h"
#include<stdio.h>
#include<locale>

int main(int argc, wchar_t* argv[])
{
    std::locale::global(std::locale(""));
    wprintf(L"Parameter sent: %s", argv[1]);
    return 0;
}

但是,如果我使用以下命令执行程序:

AppName.exe SomeText-éãö

打印:

Parameter sent: ?????????????

1 个答案:

答案 0 :(得分:4)

根据Microsoft,如果使用main,默认情况下会创建多字节字符环境。如果使用wmain,默认情况下会创建一个宽字符环境。

因此,事实证明有两种方法可以解决这个问题。我将使用中文字符作为示例,在项目的属性页的调试选项卡中将命令参数设置为“中国”(意思是“中国”)

除了语言区域设置之外,您还需要设置控制台输入和输出使用的代码页。否则,控制台可能无法正确显示您的字符。这就是你看“?????? ..”的原因,因为控制台当前使用的代码页中不存在这些字符。

1.使用多字节字符集。

// Since we use MBCS, narrow-character version main should be used
int main(int argc, char *argv[])
{
   // You console may not use the code page you want.
   printf ("%d\n", GetConsoleCP());
   printf ("%d\n", GetConsoleOutputCP());

   // To read/write Chinese characters, we set code page to 936.
   SetConsoleCP(936);
   SetConsoleOutputCP(936);

   // Set C++ locale. Same to "Chinese_China.936" here.
   locale old = locale::global(locale(""));
   locale cur;
   printf ("old locale: %s\n", old.c_str());
   printf ("new locale: %s\n", cur.c_str());

   printf("Parameter sent: %s\n", argv[1]);
   getchar();
}

输出,

1252
1252
old locale: C
new locale: Chinese (Simplified)_People's Republic of China.936
Parameter sent: 中国

2.使用Unicode。

// Since we use Unicode, wide-character version wmain should be used
int wmain(int argc, wchar_t* argv[])
{
   // You console may not use the code page you want.
   printf ("%d\n", GetConsoleCP());
   printf ("%d\n", GetConsoleOutputCP());

   // To read/write Chinese characters, we set code page to 936.
   SetConsoleCP(936);
   SetConsoleOutputCP(936);

   // Set C++ locale. Same to "Chinese_China.936" here.
   locale old = locale::global(locale(""));
   locale cur;
   printf ("old locale: %s\n", old.c_str());
   printf ("new locale: %s\n", cur.c_str());

   wprintf(L"Parameter sent: %ls\n", argv[1]);
   return 0;
}

输出,

1252
1252
old locale: C
new locale: Chinese (Simplified)_People's Republic of China.936
Parameter sent: 中国
相关问题