dcsimg
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Beginner
Oct 3, 2000

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Writing to File from Several Functions.

Question:
The code below creates a file, Basket.doc, in the current directory.

I am using a compiler with a component I would like to place in fWrite() to let me vary the entire path and file name (i.e. outName). The trouble is I want outSide to be valid from fFinish(), too. Do I need a global variable or a pointer of some kind?

char outName[] = "Basket.doc";
ofstream outSide(outName);

void fWrite() 
{
   outSide << "This is a test." <<  endl;
}

void fFinish()
{
   outSide.close();
}

int main()
{
   fWrite();
   fFinish();
}

Answer:
You certainly don't need a global variable here. Simply pass a reference to ofstream to your functions and have them access that reference:

void fWrite(ofstream & outSide) 
{
   outSide <<  "This is a test." <<  endl;
}


void fFinish(ofstream & outSide)
{
   outSide.close();
}

You will need to change main() as well: create the outSide object inside main(), and pass it the the invoked functions, as follows:

int main()
{  
 outName[] = "Basket.doc";
 ofstream outSide(outName);
 fWrite(outSide);
 fFinish(outSide);
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date