【问题标题】:c++ while loop won't exit once condition is met一旦满足条件,c ++ while循环将不会退出
【发布时间】:2019-07-13 14:12:28
【问题描述】:

我正在尝试使用 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;
   }
}

【问题讨论】:

  • 您声明了两个不同的inputFile 对象。一个与另一个完全没有关系。一旦第一个对象处于失败状态,它将保持失败状态。声明另一个具有相同名称的对象并使用它成功打开文件绝对不会改变第一个对象的失败状态。
  • 谢谢。我现在明白我的错误了。

标签: c++ while-loop ifstream


【解决方案1】:

这里的问题是您在两个不同的范围内定义了 2 个变量 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;
   }
}

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2022-01-13
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2019-01-29
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多