我如何创建一个循环来检查用户的输入,看看它是否是一个现有的文件

How can i create a loop that checks a users input to see if it is an existing file?

本文关键字:一个 输入 文件 是否是 何创建 创建 循环 检查 用户      更新时间:2023-10-16

我需要用户输入一个文件,只要用户输入存在的文件,文件就会循环。当用户输入一个不存在的文件时,程序将中断。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    string currentfile;
    int i = 0;
    do {
        cout << "Please enter a file name n";
        cin >> currentfile;
        cout << currentfile << "n";
        ifstream myfile(currentfile);
        if (myfile.good())
        {
            // display thenumber of characters, words, and lines in that file
            myfile.close();
        }
        else {
            cout << "break";
            break;
        }
        i++;
    } while(true);
    // repeat while user enters valid file name
}

当我输入一个存在的文件时,myfile.good()返回good,然后如果我尝试一个不存在的文件,myfile.good()再次返回true。如果我启动程序,我首先尝试一个不存在的文件,then myfile.good()返回false。

我不知道为什么在我输入一个有效的文件后,myfile.good()将继续返回true。

您需要检查的是:

ifstream myfile(currentfile);
if (myfile) // myfile.is_open() is fine too...
{
    // display thenumber of characters, words, and lines in that file
    myfile.close();
}
else {
    cout << "break";
    break;
}

good():

检查流是否准备好输入/输出操作,其他成员函数用于检查特定状态

检查状态标志。

要测试文件是否成功打开,您可以使用:

myfile.is_open()

然后,如果是,您将执行如下检查:eof(),…,或good().

的例子:

ifstream myfile(currentfile);
if (myfile.is_open())
{
    while ( myfile.good() ) // while ( !myfile.eof() ), ...
    {
        getline (myfile,line);
        cout << line << endl;
    }
    myfile.close();
}