0

Here is my code. I want it to ask for the name of file until it is a valid name. How will I do it? In my current code it stops after the fail.

void X() {
    string fileName;
    ifstream inFile;

    cout << "Enter the name of the file: " << endl;
    cin >> fileName;
    ifstream input;
    input.open(fileName);

    if (input.fail()) {
        cout << "Could not open the file " << fileName << endl;
    }
}
1
  • The last brace is not in the code block, you need to indent it by 4 spaces. Commented Feb 16, 2013 at 18:43

1 Answer 1

1
void X() 
{
  string fileName;
  ifstream inFile;
  do {
    cout << "Enter the name of the file: " << endl;
    cin >> fileName;
    ifstream input;
    input.open(fileName);
    if(input.fail())
    {
       cout<< "Could not open the file "<< fileName<< endl;
    }
  }
  while(input.fail())
}

should do the trick. That way, as long as the file open operation does not succeed, the code will keep on trying.

Sign up to request clarification or add additional context in comments.

5 Comments

Do you mean while (!input.fail())?
Oops, missed that. Thanks!
The loop condition makes no sense now. It should probably be inverted so that the loop is executed until the user enters a file name that can be opened. Your first version was probably correct.
Yup. I reacted too fast. It's late here. :) @David: it is while(input.fail()) because we want the loop to exit as soon as the file is opened, so only to loop if the open call failed.
@Nordin: If my answer is what you were looking for, can you accept it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.