程序运行后的效果如图:
前面刚开始都是正常的,到后来由于字符串长度设定300的问题,出现了乱码。
源码如下:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
const char *url ="http://c.biancheng.net/cplus/----原文链接//http://c.biancheng.net/view/7591.html";
//创建一个 fstream 类对象
fstream fs;
//将 test.txt 文件和 fs 文件流关联
fs.open("test.txt", ios::out);
//向test.txt文件中写入 url 字符串
fs.write(url, 300);
fs.close();
return 0;
}
分析和解决办法:
可能是由于txt文件编码问题的不同,会导致读写的时候出现乱码。
为此,修改自定义的解码函数:
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <string>
using namespace std;
//定义解码转换函数
string UTF8ToGB(const char* str)
{
string result;
WCHAR *strSrc;
LPSTR szRes;
//获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i+1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
//获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i+1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete []strSrc;
delete []szRes;
return result;
}
int main() {
const char *url ="https://blog.csdn.net/zhancf/article/details/49930969-原文链接//http://c.biancheng.net/view/7591.html";
//创建一个 fstream 类对象
fstream fs;
//将 test.txt 文件和 fs 文件流关联
fs.open("test1.txt", ios::out);
//向test.txt文件中写入 url 字符串
fs.write(url, 200);
fs.close();
char txt[200];
string msg;
ifstream infile;
infile.open("test1.txt");
if(!infile.is_open())
{
cout<<""<<endl;
exit(0);
}
while(!infile.eof())
{
infile.getline(txt,200);
msg=UTF8ToGB(txt);
cout<<msg<<endl;
}
infile.close();
getchar();
return 0;
}
效果如图:
参考来源:
https://blog.csdn.net/zhancf/article/details/49930969
http://c.biancheng.net/view/7591.html