我的作业要求我打开一个文件,但是如果没有打开,则会进行3次尝试,但是当我在第二次和第三次尝试中输入正确的文件时,仍然会出现错误,我写了'ERROR:File “ << input_filename <<“无法打开以供输入”',并转到我的else语句
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
}
答案 0 :(得分:0)
如果到达第106行,则表明文件输入成功。在那一行,您不应该增加h
。实际上,如果您想跳出循环,则应将h
保留为零(假设文件输入有效)。