Files in C++

Hello everyone, I have been looking around here for awhile and on the internet but cant seem to find the answer to my question. I am making a program that will find the longest increasing subsequence from test bench files that are already created. The problem Im having right now is that I cant figure out how I can let the user type the file name of the bench file he wants to test and have it be used. Kinda confusing to explain, so here is the code I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
    string fileBench;
    string line;
    
    cout<<"Please enter the number of the bench file you wish to use: "<<endl;
    cin>>fileBench;
    
    ifstream bench (fileBench);//this doesnt work but this is what im trying to do basically
    if (bench.is_open())
    {
                        while(! bench.eof())
                        {
                                getline(bench,line);
                                cout<<line<<endl;
                        }
                        bench.close();
    }
    else cout<<"Unable to open file"<<endl;
    
    
    system("Pause");
}


Thank you for any help.
Two things:

line 7: getline( cin, fileBench );
Some people like spaces in their filenames...

line 9: ifstream bench( fileBench.c_str() );
The iostream constructors don't take std::strings. Yes, obnoxious, I know...

OK, three things:

line 12: while (bench) or while (bench.good())

It is possible that something else goes wrong with the file, in which case the EOF flag can never be set, and you'd have an infinite loop. By testing the file for good()ness instead of just one termination condition, you guard against all termination conditions.

Hope this helps.
Last edited on
Thank you so much, I made the changes(especially the '.c_str()' one and it is reading the file the user types in.

Now that that works I can move on to the next part :D
Topic archived. No new replies allowed.