为什么设置全局的locale会影响cout输出中文?
平台为Windows XP Pro和VC2005。代码如下
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::locale;
using std::string;
int main(int argc, char *argv[])
{
string str = "a严a";
//输出全局和cout的locale名称
cout << locale().name() << endl;
cout << cout.getloc().name() << endl;
cout << "===========================" << endl;
printf(str.c_str());
cout << endl << str << endl;
cout << "===========================" << endl;
//C++方式设置全局locale
locale::global(locale(""));
//输出全局和cout的locale名称
cout << locale().name() << endl;
cout << cout.getloc().name() << endl;
cout << "===========================" << endl;
printf(str.c_str());
cout << endl << str << endl;
return 0;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
输出结果为
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
C
C
===========================
a严a
a严a
===========================
Chinese_People's Republic of China.936
C
===========================
a严a
a请按任意键继续. . .
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
程序默认的locale是“C”,这时使用printf和cout都能输出中文。在使用了locale::global(locale(""))把程序的全局的locale改成系统默认的“Chinese_People's Republic of China.936”后,printf还是照样输出中文,但cout却失败了(只输出了a)。这是为什么呢?cout的locale应该是不受全局locale的影响的(通过输出cout.getloc().name()也证实了这一点)。我还试了单独把cout的locale改成系统默认的“Chinese_People's Republic of China.936”,保持全局的locale不变,cout可以正常输出中文。可见“Chinese_People's Republic of China.936”这个locale并不是不合适的。
后来我把工程从dubug改成release,运行后出来的结果就正常了
输出结果
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
C
C
===========================
a严a
a严a
===========================
Chinese_People's Republic of China.936
C
===========================
a严a
a严a
请按任意键继续. . .
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
虽然这个问题算是暂时解决了,可心里总是放不下。想请各位大侠给解释一下该问题本质上可能是由什么引起的。谢谢。