Need help with simple file handling program

Helo

I have the following problem. This program should get a filename as its 1st argument, and then try to open it. If it doesn't get an argument, or the argument is a nonexistent file, then it will ask for a filename until it gets one, that is an existing file. After that, it should print out the first line of that file.
Now, it does this, except... if i first give it a false filename, and then a good one, it seemingly opens the file, but prints out nothing... like the file is empty, but it isn't. If i rerun the program, give it a valid filename the first time, then it writes out the first line correctly.

Any ideas of what is causing this?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc,char* argv[])
{
    ifstream f;
    bool bad_filename;
    string fname,str;
    argc >= 2 ? fname = argv[1] : fname = "no arguments";

                do
                {
                    bad_filename = false;
                    if (fname == "no arguments")
                        {
                      
                            cout << "A filename please" << '\n';
                            cin >> fname;
      
                        }
                    f.open(fname.c_str());
                    if (f.is_open())
                        { }
                    else
                        {
                            f.close();
                            bad_filename = true;
                    
                            fname = "no arguments";
                            cout << "Error trying to open file" << '\n';

                        }
                }
            while (bad_filename);

            f >> str;
            cout << str << '\n';



	return 0;
}
When you close the file you also need to clear the error condition. Make sure you have all three of:
1
2
3
                            f.close();
                            f.clear();
                            bad_filename = true;


Hope this helps.
Thanks. That f.clear() solved it.
But why is it needed ?
Topic archived. No new replies allowed.