告訴你的代碼是完全合法的,所以我想你這個「壞名」邏輯後使用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
但問題是,你仍然有原來的inputFile
這裏。 if
聲明中的inputFile
是新的std::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)。
如果用戶輸錯文件名,我想讓他們重新輸入。 – Rich 2015-03-24 21:24:27