如何显示我在第一个函数中创建的文件的内容?

时间:2018-03-28 17:56:11

标签: c++

//it is  a function to take file name and create it.   

void createfile(string filename)
{
    ofstream file;
    file.open(filename,ios::out);
    if(file.fail())
    {
        cout<<"file is failed"<<endl;
    }
    else
    {
        cout<<"file is opened"<<endl;
    }
}
//it is a function which takes name of file and display it's content.  

void displaycontent(string name) 
{
    ifstream file;
    file.open(name);
    string y;
    while(!file.eof())
    {
        getline(file,y);
        cout<<y<<endl;
    }
}

如何显示我在第一个函数中创建的文件的内容?

int main()
{

    string filename;
    cin>>filename;

    createfile(filename); 

    displaycontent(filename);
    return 0;
}

2 个答案:

答案 0 :(得分:0)

程序从不向文件写入任何内容,因此无法显示任何内容。此外,循环是错误的。如果读取文件时发生错误,file.eof()将永远不会成立,以下内容将永远循环。

void displaycontent(string name) 
{
    ifstream file;
    file.open(name);
    string y;
    while(!file.eof()) // WRONG
    {
        getline(file,y);
        cout<<y<<endl;
    }
}

相反,你想要这个(省略错误处理):

void display_file(const string &file_name) // Note pass by reference
{
    std::ifstream file;
    file.open(file_name);
    std::string y;
    while(std::getline(file,y)) {
       std::cout << y << '\n';
    }
}

或者更好,

void display_file(const string &file_name) 
{
    std::ifstream file(file_name);
    std::cout << file.rdbuf();
}

答案 1 :(得分:0)

在显示功能中调用create函数(在其他范围内)... 因为create函数是按值传递的,所以任何发生在其内部的更改都将保留在范围内