0

I've just started working on file using C++ for the first time and I would like to write a correct program which allows me to:

  1. Open the file giving the path;
  2. If it fails to open (showing which error is doesn't matter), ask a new path;
  3. Working on the file;
  4. Close the file;

The only point I can't do is the second one. I've already tryed somethink like:

do{
    cout<<"Path: ";cin>>path;
    f.open(path, ios::in);
}while(f.fail());

but if I write the path of an inexisting file and then a path of the file I want to open, the program continously ask me a new path and never stops.

P.S. = Will it be different if I want to use that condition to prevent errors while creating a new file using ios::out (for example: a file name/extension which contains illegal characters)?

Dadex
  • 119
  • 2
  • 12

1 Answers1

1

Clear the flags if its unsuccessful

f.open( path, ios::in ) ;
while( f.fail() )
{
    f.clear();
    std::cout<<"Incorrect file path, Re-Enter ";
    std::cin>>path;
    f.open( path, ios::in ) ;
}
P0W
  • 46,614
  • 9
  • 72
  • 119