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

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

2013-01-02 
新手请问这段代码有什么问题,输出末尾总有乱码#include iostream#include fstream#include stringus

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

#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';...
我也认为是这个原因
[解决办法]
一楼正解。。

热点排行