FStream help

Hey all, just wondering how I would go about asking a user via cin, to open a specific output file? Whenever I try, it just opens a file named whatever they type in. I'm trying to "force" them to type in output.txt, it's for a class. I'm still very new to c++ so anything helps, thanks a ton!

Here's what I have now:




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  do
    {
        output = "output.txt";
        cout << "Enter Output File Name: ";
        cin >> output;
        
        fout.open(output.c_str());
        if(fout.is_open())
        {
            cout << "Output File Opened Successfully." << endl;
            break;
        }
        else
        {
            cout << "Invalid file name." << endl;
            continue;
        }
    }
    while(!fout.is_open());
Last edited on
If you want to force them to type in output.txt in order to open the file, you have to do something like:

1
2
3
4
5
6
7
8
9
10
11
12
string output;
cin >> output;
if (output == "output.txt")
{
    // open file for writing, presumably
    ofstream fout(output.c_str());
    fout << "hi \n";
}
else
{
    cout << "Invalid file name\n";
}


That's a really weird design though. Why have them have to type in output.txt if the only correct answer is output.txt? It's almost like it's a password.
Last edited on
Yeah it is super weird, it's for our class so it's basically to help us check and clear cin and stuff. But anyways, thanks so much for your help!
Topic archived. No new replies allowed.