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