asking user for output filename

I'm having some trouble with getting my program to display an error message when the user enters an incorrect filename. It just skips over the loop I put in for error displaying. Here's what my code looks like (trimmed down from what it is in my real program)

#include<fstream>
#include<iostream>

using namespace std;
int main(void){
string file_out;

ofstream fout;
cerr << "Please enter the name of a file for your output data > " << endl;
cin >> file_out;
cerr << "\n\n";
fout.open(file_out.c_str( ));

while( fout.fail( ) ) {
fout.clear( );
cerr << "The attempt to create your output file, " << file_out
<< ", failed. \n\n";
cerr << "Please enter the name of another output file. Make sure you "
<< "enter the FULL name \n" << "of the file > \n";
cin >> file_out;
cerr << "\n\n";
fout.open(file_out.c_str( ));
}

system("pause");

return 0;
}

I know people here say I shouldn't use system("pause"), but that's what our teacher always does and what he tells us to do. The program skips over the while loop if I enter an invalid file location and just finishes the program. I saw someone give the completed program as an answer here once, please don't do that for me.
If a file doesn't exist fstream creates it. I don't know how to make it only open existing files. You may have to find another library, or use os specific api.
here is an example of opening files code:

#include <fstream>
int main() {
std::ofstream outputFile;
outputFile.open("out-file.txt");
if(!outputFile) {
std::cerr << “can’t open out-file.txt\n”;
std::exit(1);
}
outputFile << "here is an example of a text file..\n"
<< " the way we do it is similar to the way we send text \n"
<< " to the standard output stream" << std::endl;
}
@hamsterman: I can make it open existing files or create new ones if I enter a valid filename. The problem is that I want it to display an error message when I input a garbage filename like khlhbhgytd, and it doesn't do that.

@niross: I changed the while(fout.fail( )) to while(!fout) but that didn't make a difference to the way it compiled or ran, although it looks nicer. I write to the output file later in the program, which I didn't show. The rest of your code seems to be for when I'm typing the name of the file into the code, which isn't what my program is supposed to do. I have to ask the user for a filename and then open that file. Why do I need all the std::'s if I have #include<iostream>?

Am I doing the fout.open(file_out.c_str( )) correctly? Is that the problem line perhaps?
Problem solved! Turns out the "garbage" filenames I was inputting were interpreted as valid filenames; they were saved to the same region as the program was saved to but I didn't look there and so I didn't see them. When I inputted C:\ as a filename, then it gave me the error it was supposed to.
Topic archived. No new replies allowed.