Hello this is for my assignment for college. I just need help on how to properly declare ofstream/ifstream globally to get my program to work the proper way. Yes I know I can just declare it in Main() and use pass by reference. ( Did that on the first project this semester) But it was suggested I used it as a Global declaration instead. And it is written down in the instructions of this new assignment to do so.

I've tried searching through google, going through my c++ textbook. But I can't find a good example of using ofstream/ifstream globally to satisfy all of my functions outside of main that need to either read/write or both from text files.

Edit: I need to Declare ofstream/ifstream globally and also open them globally.

Thanks!

Recommended Answers

All 9 Replies

#include statements

using statements

global vars ie 
ofstream fout;
or
ifstream fin;

function prototypes

int main()
{ //...

this is the style i use

I've tried this :

#include<fstream>

ofstream outFile;
ifstream inFile;

outFile.open("Data.txt");
inFile.open("Maze.txt");

i get errors on the last two statements.

Sorry I should have been more direct and stated that I know how to declare ofstream/ifstream globally just not open them globally.

Put your statements of lines 6 and 7 into a function.

If you already know what files you are going to use than i would just use

ofstream outFile("Data.txt");  
ifstream inFile("Maze.txt");

Put your statements of lines 6 and 7 into a function.

If I did that I wouldn't be able to do this :

void function1()
{
   outFile << Stuff here ;
}
void function2()
{
  inFile >> Stuff here;
}
main()
{
 outfile << stuff here;
 infile >> stuff here;
}

would it?

If you already know what files you are going to use than i would just use

ofstream outFile("Data.txt");  
ifstream inFile("Maze.txt");

But would that open the files up for read/write access for my program?

The problem I'm having is having both text files open for all of my functions to write/read from.

If I did that I wouldn't be able to do this :

void function1()
{
   outFile << Stuff here ;
}
void function2()
{
  inFile >> Stuff here;
}
main()
{
 outfile << stuff here;
 infile >> stuff here;
}

would it?

Why not?

Ok maybe I'm not getting what your trying to help me with.

When you say just put those lines in a function. Do you mean in each function or in its own function? I've tried putting it in each function, but comes up with errors.

And if you mean put it in its own Function, how would I go about that?

Update:

Was thinking hard about it for awhile and decided to try it the way I had before. Turns out it was global all along but my code i was trying to print out didn't agree with it.


Thanks anyways!

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.