D语言的string 是utf-8的,而cmd 的是ANSI的,因字符编码格式不同,导致不能正确显示中文。
采用以下两种方式可以很好的处理这个问题。
方式一、在你的d文件中填加如下代码:(这种方式可以不用修改cmd下的任何设置,方便你的客户使用你的程序)
extern(C) int setlocale(int, char*);
static this()
{
import core.stdc.wchar_;
import core.stdc.stdio;
fwide(core.stdc.stdio.stdout, 1);
setlocale(0, cast(char*)"china");
}
----------------------例子-------------------------------------------------<pre name="code" class="plain">module hello;
import std.stdio;
extern(C) int setlocale(int, char*);
static this()
{
import core.stdc.wchar_;
import core.stdc.stdio;
fwide(core.stdc.stdio.stdout, 1);
setlocale(0, cast(char*)"china");
}
void main()
{
writeln("你要去哪儿玩",",公园?",",电影院?");
string s = readln;
writeln(s,"hello,确定吗?!");
wstring str ="拜拜!";
a(str);
writeln(str," length is ",str.length);
}
void a(wstring msg)
{
writeln("the string is ",msg);
}
------------编译
dmd hello ← 编译
hello ← 执行
注意:1、'printf' 不能正确显示中文,但用D以后,一般人很少再使用它。
2、请注意保存代码为utf-8编码。
方式二、在你的main函数中填加如下代码,并修改cmd的字体为:'Lucida Console'
import std.process;
executeShell("chcp 65001");
--------------------------------end------------------------
(如何你不想再用 65001,那在cmd下,键入命令:chcp 936 ,再把字体修改为 '宋体')