检查ifstream,出错后不起作用?

Checking ifstream, doesn't work after an error?

我在下面附上了我的代码。如果我删除 if 语句以检查文件是否已打开,此序列将起作用。为什么它不能与 if 语句一起使用?此外,如果我第一次提供正确的文件名,它的工作方式如下所示。如果我先输入错误的文件名,它只会挂断。

感谢您的帮助!

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream inputFile(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}

你显示的代码是完全合法的,所以我想你在这个 "bad filename" 逻辑之后使用 inputFile:

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream inputFile(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}
// USING inputFile here

问题在于,您在这里仍然拥有原始 inputFileif语句里面的inputFile是一个newstd::ifstream。如果您使用不同的名称,可能会更容易看到:

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream differentInputFile(fileName.c_str()); //HERE
}
else
{
    cout << "Input file opened successfully!" << endl;
}

关闭坏文件并用正确的文件名重新打开的正确方法是:

inputFile.close();
inputFile.open(fileName.c_str());

那么完整的代码就变成了

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    inputFile.close();
    inputFile.open(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}

还建议启用警告。我的建议是使用 -Wall -Wextra -Wshadow -pedantic -Wfatal-errors(适用于 gcc 和 clang)。