0
我收到一个运行程序的错误,该程序演示了如何通过引用函数传递文件流对象。引用创建错误的fstream对象
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//function prototypes
bool openFileIn(fstream &, string);
void showContents(fstream &);
int main(){
fstream dataFile;
if (openFileIn(dataFile, "demofile.txt"))
{
cout << "File opened successfully.\n";
cout << "Now reding data from the file. \n\n";
showContents(dataFile);
dataFile.close();
cout << "\nDone. \n";
}
else
cout <<"File open error! "<< endl;
return 0;
}
//******************************************************************
//Definition of function openFileIn. Accepts a reference to an
//fstream object as an argument. The file is opened for input.
//The function returns true upon success, false upon failure.
//******************************************************************
bool openFileIn(fstream& file, string name)
{
file.open(name, ios::in); //error occurs here
if (file.fail())
return false;
else
return true;
}
//*******************************************************************
//Defintion of function showContents. Accepts an fstream reference
//as its argument. Uses a loop to read each name from the file and
//displays it on the screen.
//*******************************************************************
void showContents(fstream &file)
{
string line;
while(file >> line)
{
cout << line << endl;
}
}
在“openFileIn()”函数时出现错误:制作到file.open调用(名称,内部监督办公室::中)功能,当程序失败。 'file.open()'调用失败并出现错误。 这里是堆栈跟踪:
这不是一个堆栈跟踪;你的程序不能编译。错误消息告诉你到底是什么问题。 –
尝试'file.open(name.c_str(),ios :: in);' – SHR