0

I am working on an example for a class and the build succeeds, but when it runs, it just hangs and won't complete. Not sure what I'm doing wrong?

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

int main(int argc, char *argv[]) {

istream *fin = &cin;
if(argc > 1) 
{
 ifstream infile(argv[1], ios::in);
 if (!infile) return 1;
      fin = &infile;
    	}

 while (1)
 {
    char c;
    fin->get(c);
      		
if (! *fin) break;
    cout.put(c);
    }
    return 0;
  }
2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by declain
0

infile is local to the if statement and the file gets closed when the if statement ends. Inside the loop, the file is closed, the object pointed to by the pointer is gone and you are not allowed to dereference the pointer anymore. Even if you have a pointer to an object, you need to make sure that the object still exists as long as the pointer is being used:

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

int main(int argc, char *argv[]) {
    istream *fin = &cin;
    ifstream infile;

    if(argc > 1) 
    {
        infile.open(argv[1], ios::in);
        if (!infile) return 1;
        fin = &infile;
    }

    while (1)
    {
        char c;
        fin->get(c);

        if (! *fin) break;
        cout.put(c);
    }
    return 0;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.