Global ifstream variable

May 11, 2017 at 9:14pm
Hi,

Please consider this following piece of code.
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
   ifstream objfile("log.txt");
   //
   for loop:
   process();
}

void process()
{
    // some processing
    // objfile.seekg(...)  //couldn't use objfile 


To use objfile in process() I thought of declaring it outside the main.

1
2
3
4
5
6
7
8

ifstream objfile

int main()
{
    objfile(somefileName); // gives error
}


error C2064: term does not evaluate to a function taking 1 arguments

Can you please suggest how to use objfile in process() function.
May 11, 2017 at 9:19pm
Functions can take parameters. Pass the ifstream variable to the function as a parameter.

1
2
3
void process(ifstream& some_stream)
{
  ...
May 12, 2017 at 4:22pm
Hi,

I would like to use objfile in several different functions. Rather than passing it as parameter across all those functions, is it possible to just declare it globally and use in different functions?
May 12, 2017 at 4:28pm
Rather than passing it as parameter across all those functions, is it possible to just declare it globally and use in different functions?

Yes it's possible. But you should strive to eliminate global variables whenever possible.

To use the global instance in this case you'll want to open() the file in main().
Last edited on May 12, 2017 at 4:30pm
Topic archived. No new replies allowed.