首页 > 解决方案 > C++ 创建一个函数来读取 .txt 文件并检查以确保文件存在,但我的循环不起作用

问题描述

我正在尝试创建一个函数来读取文件,检查以确保它存在(如果它不再要求文件名),然后打印“正在加载...”如果它确实找到了文件。

但是,循环只经过一次。它打印出“文件错误:文件不存在!” 然后结束程序。有任何想法吗?如果您需要更多信息,请告诉我!

void find_board(string fileName)
{
bool filefound = 0;
ifstream in_stream;

do
{
    cout << "Enter the name of the file containing the board: ";
    cin >> fileName;

    in_stream.open(fileName.c_str());

    if (in_stream.fail())
    {
        filefound = 0;
        cout << "FILE ERROR: File does not exist!" << endl;
        exit (EXIT_FAILURE);
    }
    else
    {
        filefound = 1;
    }
} while (filefound == 0);

cout << endl << "Loading..." << endl;

return;
}

标签: c++fileloopsifstream

解决方案


exit (EXIT_FAILURE);为了什么?


推荐阅读