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