首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

初学者,关于char*和string之间的一点有关问题

2013-12-04 
菜鸟求助,关于char*和string之间的一点问题#include stdafx.h#include iostream#include string#inc

菜鸟求助,关于char*和string之间的一点问题

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int lenght;
char* buf;
ifstream infile;
infile.open("example.txt", ios::binary);
infile.seekg(0, ios::end);
lenght = infile.tellg();
infile.seekg(0, ios::beg);
buf = new char[lenght];
infile.read(buf, lenght);
infile.close();

cout.write(buf, lenght);
cout<<endl;
string str1(buf);
cout<<str1<<endl;
cout<<lenght<<endl;
cout<<strlen(buf)<<endl;
system("pause");
return 0;
}

将buf的值传递给str1后显示出来多了一些乱码,两次的长度也不同。想不通,求指点。万谢万谢!! char* string
[解决办法]
对于\0等结束符处理。
[解决办法]
buf = new char[lenght]; => buf = new char[lenght+1];
然后memset(buf,0,lenght+1);
[解决办法]
别忘了结束符0
[解决办法]
编码是 utf8 , 基本是 3个 字节 为 一个 汉字。

热点排行