Thread: How to get input from multiple files?

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    9

    How to get input from multiple files?

    Hi,

    I'm creating a program that needs to read in a filename from stdin, open it, and do some processing, then repeat the process until the user enters "quit." I get the first file processed fine, but it crashes when I try to open the second file. Actually, the program enter the if (! inFile) section of code even if the second filename is correct and the file exists. I think it's because the filestream is bad at the end of the first file. There must be some way to reuse the same file handle. Here is what I've got:
    Code:
    int main()
    {
    	ifstream inFile;
    	string inFilename;
    	Maze m1;
    
    	cout << "Enter filename with stored maze or \"quit\" to end: ";
    
    	cin >> inFilename;
    	inFile.open(inFilename.c_str());
    
    	while(inFilename != "quit")
    	{
    		// make sure input file was opened properly
    		if (! inFile)
    		{
    			cout << "Error opening file \"" << inFilename.c_str() << "\"\nProgram will now exit.\n";
    			return 1;
    		}
    
    		m1.readMaze(inFile);
    		m1.printMaze();
    		inFile.close();
    
    		cout << "Enter filename with stored maze or \"quit\" to end: ";
    		cin >> inFilename;
    		inFile.open(inFilename.c_str());
    	}
    
    	return 0;
    }
    Any idea what I've got wrong? Thanks!

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Check out this older thread on pretty well the exact same topic.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    9
    Thanks, but I just realized I was passing the ifstream object to my function by value instead of by reference! All fixed now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help creating multiple text files
    By Tom Bombadil in forum C Programming
    Replies: 19
    Last Post: 03-28-2009, 11:21 AM
  2. Multiple Cpp Files
    By w4ck0z in forum C++ Programming
    Replies: 5
    Last Post: 11-14-2005, 02:41 PM
  3. Need help with input streams from multiple source files
    By orikon in forum C++ Programming
    Replies: 2
    Last Post: 10-08-2005, 02:56 PM
  4. using a class in multiple source files???
    By Crossbow in forum C++ Programming
    Replies: 9
    Last Post: 06-18-2002, 07:42 PM
  5. Multiple .c files
    By GaPe in forum Windows Programming
    Replies: 3
    Last Post: 03-26-2002, 08:27 AM