Greetings, I have a C++ program in which I am trying to print to a file, but using the following commands it isn't working. "payrecord.txt" is created, but blank. I suspect it has to do with my choice of making the displayResults function a "void", but I am not certain. When the code within "displayResults" wasn't a function but instead part of main(), I had only to use "myfile" before the text, but using that in the void() displayResults function results in an error that says:

In function void displayResults()':myfile' undeclared (first use this function)
(Each undeclared identifier is reported only once for each function it appears in.)

Any ideas or advice will be gladly accepted. Thanks very much, relevant (I hope) snips of code follow.

#include<iostream>
#include<fstream>
#include<iomanip>
.
.
.
void displayResults();
.
.
.
int main()
{
    ofstream myfile;
    myfile.open("payrecord.txt");

    for(i=0; i<Count; i++)
    {

.
.
.          
     }

     displayResults();
     myfile.close();

system("pause");
return 0;

} 

.
.
.

void displayResults(void)
{    
     cout << "Fst Name".....
     //changing either of the "cout" statements in this function to myfile
     //results in the error message above when compiling
     for(j=0; j<Count; j++)
     {
            cout << First_Name[j].....

     }
}

Recommended Answers

All 4 Replies

Your function displayResults() has no idea that myfile exists.

There are a few things you can do. You can declare ofstream myfile as global, pass it through the function as a parameter or declare it within the function. If you are not writing to the file anywhere else but within displayResults() I would recommend creating myfile in there.

Thanks for your response, sfuo.

How would I declare it within the function? It's not a variable, and doesn't have a datatype, so?

Everything has a datatype. In this case ofstream is the datatype and myfile is the instance of it. Just because it is not a basic datatype (ie int, float, char..) does not mean it is not a type. Obviously a stream type is a lot more complicated than other objects since it interacts with user input/output but for the most part objects are just made up of a bunch of basic datatypes.

Here is an example of declaring and using ofstream within the function.

#include <iostream>
#include <fstream>
using namespace std;

void displayResults()
{
	ofstream myfile("payrecord.txt");

	myfile << "Fst Name" << endl;

	myfile.close();
}

int main()
{
	displayResults();


	return 0;
}

Thanks so much for your response. I will try to figure this out using this info - regards.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.