jjesh
jjesh

Reputation: 9

How do I open a file from a function for the whole code?

I'm working on a simple c++ script and wanted to put the whole process of opening up a file inside a function. However, when I try, I get errors in my main function. Can anyone help me? This is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

string openFile(string fileName);
int main(void)
{
    string fileName;
    cout << "Please input the file name (including the extension) for this code to read from." << endl;
    cin >> fileName;

    openFile(fileName);

    fout << "File has been opened" << endl;
    return 0;
}

string openFile(string fileName)
{
    ifstream fin(fileName);
    if (fin.good())
    {
        ofstream fout("Output");
        cout << fixed << setprecision(1);
        fout << fixed << setprecision(1);
        //Set the output to console and file to be to two decimal places and 
        //not in scientific notation
    }
    else 
    {
        exit(0);
    }
}

Upvotes: 0

Views: 7030

Answers (2)

Saravanan
Saravanan

Reputation: 1440

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <iomanip>

    using namespace std;

    ofstream fout;
    string openFile(string fileName);
    void closeFile();

    int main(void)
    {
        string fileName;
        cout << "Please input the file name (including the extension) for this code to read from." << endl;
        cin >> fileName;

        openFile(fileName);
        if (fout.good()) //use fout in any way in this file by cheking .good()
           cout << "File has been opened" << endl;
        closeFile();
       return 0;
    }

    string openFile(string fileName)
    {
        cout << fixed << setprecision(1);
        fout.open(fileName.c_str());
        if (fout.good()) {
           fout << fixed << setprecision(1);
           cout<<"Output file opened";
        }
    }
    void closeFile()
    {
       fout.close();
    }

Upvotes: 1

Pranit Kothari
Pranit Kothari

Reputation: 9841

Your code has lot many flaws,

  1. fout << "File has been opened" << endl;, should be,

    cout << "File has been opened" << endl;

  2. You cannot redifine same varible again.

    ofstream fout("Output");// first 
    cout << fixed << setprecision(1);
    fout << fixed << setprecision(1);
    //Set the output to console and file to be to two decimal places and 
    //not in scientific notation
    ofstream fout("Tax Output.txt");//second
    

Give some other name to variable in last line.

  1. You are passing std::string, where you should pass const char *,

ifstream fin(fileName);

should be,

ifstream fin(fileName.c_str());

Upvotes: 0

Related Questions