c++ - 如何在这里创建一个循环? C++

标签 c++ loops

这是我的代码。我希望它询问文件名,直到它是一个有效名称。我将如何做?在我当前的代码中,它在失败后停止。

void X() {
    string fileName;
    ifstream inFile;

    cout << "Enter the name of the file: " << endl;
    cin >> fileName;
    ifstream input;
    input.open(fileName);

    if (input.fail()) {
        cout << "Could not open the file " << fileName << endl;
    }
}

最佳答案

void X() 
{
  string fileName;
  ifstream inFile;
  do {
    cout << "Enter the name of the file: " << endl;
    cin >> fileName;
    ifstream input;
    input.open(fileName);
    if(input.fail())
    {
       cout<< "Could not open the file "<< fileName<< endl;
    }
  }
  while(input.fail())
}

应该可以解决问题。这样,只要文件打开操作不成功,代码就会继续尝试。

关于c++ - 如何在这里创建一个循环? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913662/

相关文章:

c++ - 从 std::vector 中移除一个项目

python - 在不同的循环python中迭代四个列表

c - C中的for循环混淆

javascript - 在 Javascript 和 Vue 中搜索另一个数组时是否可以修改一个数组的值?

python - 提高循环 numpy 数组的速度

c# - MFC 应用程序中的 WPF System.Windows.Navigation.NavigationWindow

C++:POD 优缺点

objective-c - 从头到尾循环Nsmutable图像数组

c++ - 检查父构造函数是否有参数

c++ - C++中的桶指针是什么?