почему мой код пропускает оператор if и переходит к другому, когда я открываю файл - PullRequest
0 голосов
/ 13 ноября 2018

мое задание просит меня открыть файл, но если он не открывается, вам дают 3 попытки, но когда я ввожу правильный файл на второй и третьей попытке, он все равно выдаст мне ошибку, которую я написал «ОШИБКА: Файл «<< input_filename <<» не может быть открыт для ввода «» и переходит к моему оператору else </p>

char input_filename [90]; вход ifstream;

cout << "Type the name of the input file which will hold the simulation results : " << endl;
cin>> input_filename;
input.open(input_filename);
if (input.fail())//if the file doesn't open it will go to the do while loop error message
{   

    int i = 0;
    int h = 0;
     do
    {   
        cout << "ERROR: File " << input_filename << " could not be opened for input" << endl;

        cin >> input_filename;// allows user to reinput filename
        input.open(input_filename);//opens file 
        if ( !input.fail()) 
        {   
            cout << "if statement" << endl;
            h++;// if h doesn't equal 1 it goes out of the loop
        }
            else
            {   
            cout << "else statement" << endl;
                i++;//post-decrement allows for 2 more tries to input file
            }
        if (i >= 2) 
        {
            cout << "ERROR: You exceeded maximum number of tries allowed" << endl;
            cout << "while entering the input file name" << endl;
            return 1;// return 1 represents the error of the input not opening after the 3rd time of inputing
        }
     } while (i < 2 && h != 0);// do while because it need to be a post condition for two varibles


}

1 Ответ

0 голосов
/ 13 ноября 2018

Если вы достигнете строки 106, это означает, что ваш файл введен успешно. В этой строке вы НЕ должны увеличивать h. На самом деле вы должны оставить h на нуле, если хотите выйти из цикла (при условии, что ввод файла сработал).

...