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;
  }

Recommended Answers

All 2 Replies

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;
}

Thanks!

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.