我想讀取僅包含字符串的文本文件。它正在編譯和打開,但在閱讀時只顯示與文件中的字符無關的垃圾。閱讀fstream返回垃圾
任何人都可以看到有什麼問題嗎?
#include <iostream>
#include <fstream>
using namespace std;
fstream myfile;
char* input;
void main(void)
{
myfile.open("H://fstream_test.txt", fstream::in);
if(myfile.fail())
{
cout<<"error"; exit(0);
}
cout<<"file is open";
int beginning = myfile.tellg();
myfile.seekg(0, fstream::end);
int end = myfile.tellg();
int size = end-beginning;
cout<<size; //returns 15
input = new char[size];
myfile.read(input,size);
cout<<input;
//returns junk
//for(int i=0;i<size;i++)
//cout<<input[i];
//returns the same;
}
末編輯爲:
input = new char[size];
myfile.seekg(0, fstream::beg);
while(!myfile.eof())
{
myfile.read(input,size);
}
cout<<input;
system("pause");
input = new char [size];不刪除[]。這是內存泄漏。改爲使用標準庫容器。 –