新手请问这段代码有什么问题,输出末尾总有乱码

MapzChen 2012-12-27 11:04:03
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
ifstream fileIn;
char* buff;
long size;
fileIn.open("testIO.cpp",ios::binary|ios::in|ios::ate|ios::_Nocreate);
if(!fileIn){
cout << "open file err" << endl;
system("pause");
return -1;
}
size = fileIn.tellg();
buff = new char[size];
fileIn.seekg(0,ios::beg);
fileIn.read(buff,size);
cout << buff << endl;
fileIn.close();
system("pause");
}


vs2012建立空项目编译后
buff的结尾总会多输出几个乱码
输出结果
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
ifstream fileIn;
char* buff;
long size;
fileIn.open("testIO.cpp",ios::binary|ios::in|ios::ate|ios::_Nocreate);
if(!fileIn){
cout << "open file err" << endl;
system("pause");
return -1;
}
size = fileIn.tellg();
buff = new char[size];
fileIn.seekg(0,ios::beg);
fileIn.read(buff,size);
cout << buff << endl;
fileIn.close();
system("pause");
}铪


在macOS C++下编译正常,没有结尾的乱码
...全文
159 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
MapzChen 2012-12-27
  • 打赏
  • 举报
回复
已解决,多谢各位
szulee 2012-12-27
  • 打赏
  • 举报
回复
1楼大神各种神速秒杀。
proorck6 2012-12-27
  • 打赏
  • 举报
回复
一楼正解。。
vipjeffreylee 2012-12-27
  • 打赏
  • 举报
回复
引用 1 楼 turingo 的回复:
应该是缺少结束符的缘故,加上试试看: C/C++ code?123456... buff = new char[size + 1]; fileIn.seekg(0,ios::beg); fileIn.read(buff,size); buff[size] = '\0';...
我也认为是这个原因
图灵狗 2012-12-27
  • 打赏
  • 举报
回复
应该是缺少结束符的缘故,加上试试看:

...
  buff = new char[size + 1];
  fileIn.seekg(0,ios::beg);
  fileIn.read(buff,size);
  buff[size] = '\0';
...

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧