读书人

新手请教这段代码有什么有关问题输出

发布时间: 2013-01-02 13:08:45 作者: rapoo

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

#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++下编译正常,没有结尾的乱码

[解决办法]
应该是缺少结束符的缘故,加上试试看:

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

[解决办法]
引用:
应该是缺少结束符的缘故,加上试试看:
C/C++ code?123456... buff = new char[size + 1]; fileIn.seekg(0,ios::beg); fileIn.read(buff,size); buff[size] = '\0';...
我也认为是这个原因
[解决办法]
一楼正解。。

读书人网 >C++

热点推荐