-3
//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;
    }
}

How can I display the content of the file that I already created in the first function?

int main()
{

    string filename;
    cin>>filename;

    createfile(filename); 

    displaycontent(filename);
    return 0;
}
shrouq
  • 11

2 Answers2

0

The program never writes anything to the file, so there is no content to display. Also, the loop is faulty. If an error occurs reading the file, file.eof() will never be true, the following will loop forever.

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

Instead, you want this (omitting error-handling):

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';
    }
}

Or better yet,

void display_file(const string &file_name) 
{
    std::ifstream file(file_name);
    std::cout << file.rdbuf();
}
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
0

call the create function inside the display function (in else's scope )... as the create function is passed by value so any changes that will happen to what's inside of it will stay within the scope