Simple opening a input file

Nov 10, 2008 at 2:43am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string fileName;
ifstream inFile;	

cout << "What file do you want to gather data from? ";
cin >> fileName;
inFile.open( fileName.c_str() );

while( inFile.fail() )
{

	cerr << "Could not connect, try again: ";
	cin >> fileName;
	inFile.open( fileName.c_str() );

}
This should keep bothering the user until the ifstream can open up the file. However, when I type in a file that IS connectable to after messing up the first time, it just keeps saying "could not connect". Example of success and example of failure:

What file do you want to gather data from? myData.tx
t
... program successful, works fine

---

What file do you want to gather data from? myD.txt
Could not connect, try again: dadasd.txt
Could not connect, try again: myData.txt
Could not connect, try again:

... what the heck, correct input and it still fails?
Last edited on Nov 10, 2008 at 2:48am
Nov 10, 2008 at 3:13am
You have to put an inFile.clear() IIRC...it sets the fail bit which needs to be reset before you can do other ops on the stream.
Nov 10, 2008 at 3:17am
Yes, my notes has something that says "use .clear when file fails to open"! So I was leaning towards that. However, I do not know where to put inFile.clear(), could you show me which line it belongs in? If I put it anywhere in the while loop, it doesn't help.
Last edited on Nov 10, 2008 at 3:51am
Nov 10, 2008 at 3:50am
Think of it this way:
Where would you need to put it so that it is called before you open it again?
Nov 10, 2008 at 3:51am
Got it! To exit the fail state, we need to clear the ifstream by using inFile.clear() right before the .open() in the while loop.

Thanks!
Nov 10, 2008 at 3:53am
No problem :)
Topic archived. No new replies allowed.