使用easyx制作游戏需要读写文件时遇到编码问题的解决方法
一、编码问题
例如我们需要从file.txt中读取文字,再使用outtextxy()
函数向窗口绘制文字。
查找easyx的官方文档可知,该函数有两个重载,分别为:void outtextxy(int x, int y, lpctstr str)
和void outtextxy(int x, int y, tchar c)
。
如果我们的file.txt文件使用gbk或者gb2312编码的话,会导致vs编译器混合utf-8编码和gbk编码,导致程序不能正确绘制文字。
编码问题一直是令人头痛的问题,这里给出通用的方法论,希望能够带来一些帮助。
二、解决方法
1.重新编码txt文件
首先使用vscode打开file.txt文件,确保文件编码为utf-8。如下图:
如果不是utf-8编码,点击选择编码,通过编码重新打开,选择utf-8编码,这时原来的内容会变成乱码,将原来的内容删除,重新输入,保存即可。具体的操作如下图:
2.代码部分
首先,我们需要用到std::wstring_convert
,这个标准库需要头文件#include<codecvt>
,我们定义string str
,用static std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
定义我们所需要的从utf-8编码的字符串到宽字符串的转换器。
打开文件,读取文件内容到str内,使用from_bytes(str)
函数即可实现字符串的转换,又由于outtextxy没有使用wstring的重载,使用wstring的成员函数c_str()
即可转换成wchar_t
字符串,最终,我们用这样的代码将文字绘制在窗口上outtextxy(10, 10, converter.from_bytes(str).c_str());
。
效果如图:
完整代码如下:
#include<fstream> #include<codecvt> #include<string> #include<iostream> #include<graphics.h> std::string str; int main() { initgraph(500, 500); static std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::ifstream infile("file.txt"); if (!infile) { std::cerr << "无法打开文件" << std::endl; return 0; } std::getline(infile, str); infile.close(); while (true) { outtextxy(10, 10, converter.from_bytes(str).c_str()); } }
三、问题延伸
如果我们需要在程序内使用inputbox
对话框输入,并将输入的内容正确保存在文件里,该如何操作呢。
首先查看inputbox
的参数列表bool inputbox(lptstr pstring, int nmaxcount, lpctstr pprompt = null, lpctstr ptitle = null, lpctstr pdefault = null, int width = 0, int height = 0, bool bonlyok = true);
,其中大部分是默认参数,这里不做解释,重点是第一个参数,inputbox
只接受&wchar_t
的参数,因此,假设输入的字符串最大长度为256,我们定义tchar buffer[256];
数组来接收输入,写下这样的代码来弹出对话框inputbox(buffer, 256, _t("请输入:"), _t("输入框"), null, 0, 0, true);
打开文件,定义std::string str;
,仍然使用我们刚才定义的转换器,使用to_bytes()
函数,即可将输入的内容转换为utf-8字符串。再进行输入即可。
完整代码如下:
#include<fstream> #include<codecvt> #include<string> #include<iostream> #include<graphics.h> int main() { initgraph(500, 500); static std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; tchar buffer[256]; inputbox(buffer, 256, _t("请输入:"), _t("输入框"), null, 0, 0, true); std::ofstream outfile("file.txt"); if (!outfile) { std::cerr << "无法打开文件" << std::endl; return 0; } std::string str = converter.to_bytes(buffer); outfile << str; outfile.close(); }
发表评论