满足条件后,c ++ while循环不会退出

时间:2019-07-13 14:12:28

标签: c++ while-loop ifstream

我正在尝试使用while循环来确保已使用“ ifstream inputFile(fileName);”打开文件。如果我首先输入正确的文件名,则while循环条件(!inputFile)正确计算为false,并被跳过。如果我输入了错误的文件名,则while循环正确地评估为true并被输入。在while循环中,如果输入正确的文件名,则inputFile的值的确从0更改为1(我使用cout语句检查)-但是while循环不会停止。

#include <iostream> 
#include <fstream>
#include <string>
using namespace std;

int main(void) {
   string fileName;

   cout << "\nEnter a file name: ";
   cin >> fileName;

   ifstream inputFile(fileName);

   while(!inputFile) {
      cout << "File not found, please enter another file: ";
      cin >> fileName;    
      ifstream inputFile(fileName);

      // just added to check values
      cout << "fileName is: " << fileName << endl;
      cout << "inputFile is: " << inputFile << endl;
   }
}

1 个答案:

答案 0 :(得分:1)

这里的问题是,您在两个不同的范围内定义了两个变量inputFile。第一个在while条件中进行评估,第二个在每次while迭代中创建和销毁,并且从不评估。

考虑尝试:

#include <iostream> 
#include <fstream>
#include <string>
using namespace std;

int main(void) {
   string fileName;

   cout << "\nEnter a file name: ";
   cin >> fileName;

   ifstream inputFile(fileName);

   while(!inputFile) {
      cout << "File not found, please enter another file: ";
      cin >> fileName;    
      inputFile.open(fileName); // <== Here is the change

      // just added to check values
      cout << "fileName is: " << fileName << endl;
      cout << "inputFile is: " << inputFile << endl;
   }
}