2016-04-26 55 views
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()'调用失败并出现错误。 这里是堆栈跟踪:

Stacktrace

+2

这不是一个堆栈跟踪;你的程序不能编译。错误消息告诉你到底是什么问题。 –

+0

尝试'file.open(name.c_str(),ios :: in);' – SHR

回答

2

open函数重载采取的std :: string作为参数,is defined starting from C++11

您可能会使用旧的编译器,因此您需要使用const char *的旧开放签名。

尝试:

file.open(name.c_str(), ios::in); 

我得到一个错误运行演示如何提交 流对象可以参考函数传递的程序。使得在file.open调用(名称,内部监督办公室::中)功能

请注意,你的程序是不是在编译时都失败 程序。您在输出中看到的是编译错误,而不是堆栈跟踪。