File handling functions

Hello, I'm almost at the finish line writing this program, but I've fallen at the last hurdle, something I cant get my head around, so any suggestions would be great.

This is a function in a Data class that prints out the data stored in an array.

1
2
3
4
5
6
7
8
void Data::toString()
{
    cout        << _testONE   << ":"
                << _testTWO   << ":"
                << _testTHREE << ":"
                << _testFOUR  << ":"
                << _testFIVE  << endl;
}


However, the next stage is to print these results to a file instead of the screen.

The problem I have is that I can’t use the ofstream name in that function without declaring it within it. I need to somehow pass this to the function.

I want a function along the lines of this,

1
2
3
4
5
6
7
void Data::fileHandling() //int or void?
{
	char fileName[30];
	cin >> fileName;
	ofstream outputFile;
	outputFile.open(fileName,ios::app);
}


and then the next function called would be void Data::toString() to write the data, and close the file. What would I have to put into the parameters to make this work?

Any help would be much appreciated, thanks.
You could pass a std::string to fileHandling and you would want to pass an ofstream& to toString. I would suggest naming toString to something else as that's a common name for a method that returns a string representation of the object.
Last edited on
Thanks, I can understand how I need to pass ofstream, but I getting in a big mess actually putting it in my code. Below is a basic layout of how I am calling and declaring each function, without the parameters. Would I have to put ofstream& into each printResults()? And same for std::string to fileHandling.

in main.cpp
1
2
3
4
5
6
7
{
...
data1.fileHandling();
...
list1.front()->printResults();
...
}


in the .h file
1
2
3
4
5
6
7
{
public:
...
void printResults();
void fileHandling();
...
}


in the .cpp file
1
2
3
4
5
6
7
8
9
void Data::printResults()
{
...
}

void Data::fileHandling()
{
...
}
Would I have to put ofstream& into each printResults()?

Putting the name of the parameter is optional in the declaration regardless of if the parameter is ignored in the definition. At the function call site, you would pass in the variable.

I would suggest reading this (and related) before going further:
http://cplusplus.com/doc/tutorial/functions/
Topic archived. No new replies allowed.