Problems using two files

This is a discussion on Problems using two files within the C++ Programming forums, part of the General Programming Boards category; In the example program, I want to read from two files. The first files works fine but I do not ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    2

    Problems using two files

    In the example program, I want to read from two files.
    The first files works fine but I do not get an output from the second one. I am using Visual C++.

    thanks for your help,
    dwygal

    Code:
    #include<iostream>
    #include<fstream>
    
    using namespace std;
    
    int main()
    
    {
    	ifstream inData;		//declaring file variable
    
    	inData.open("C:\\Documents and Settings\\Wygal\\Desktop\\textFiles\\groc-inv.txt");
    
    	char ch;				//declaring character variable
    
    
    
    	while(!inData.eof())	//getting the multiple line file
    	{
    		inData.get(ch);
    		cout << ch;
    	}
    	cout << endl;      	
    	
    	inData.close();			//closing first file
    
    
    /*_____________________________OPEN SECOND FILE_____________________________________*/
    	inData.open("C:\\Documents and Settings\\Wygal\\Desktop\\textFiles\\grocery.txt");
    
    	inData >> ch;			//TRYING TO GET A CHARACTER
    
    	cout << ch << endl;		//TRYING TO PRINT CHARACTER
    							
    							//THIS ACTION IN NOT WORKING
    
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > inData.close(); //closing first file
    Although this really shouldn't be necessary, you may need to clear the error flags before opening the next file, so call clear() after the close():
    Code:
    	inData.close();			//closing first file
    	inData.clear();
    Code:
    >	while(!inData.eof())	//getting the multiple line file
    >	{
    >		inData.get(ch);
    >		cout << ch;
    >	}
    Never use eof() to control a file reading loop. Instead use the return value of the read itself:
    Code:
    	while(inData.get(ch))	//getting the multiple line file
    	{
    		cout << ch;
    	}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems saving audio files
    By JoeJTaylor in forum C++ Programming
    Replies: 0
    Last Post: 04-23-2006, 04:10 PM
  2. Replies: 6
    Last Post: 08-13-2003, 05:35 AM
  3. Problems openning huge files
    By acoelho74 in forum C Programming
    Replies: 4
    Last Post: 02-11-2003, 07:02 PM
  4. Using c++ standards
    By subdene in forum C++ Programming
    Replies: 4
    Last Post: 06-06-2002, 10:15 AM
  5. Problems with resource files
    By Unregistered in forum C++ Programming
    Replies: 18
    Last Post: 08-31-2001, 09:45 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21