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

时间:2013-06-12 00:12:27

标签: c++

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

#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()返回良好,然后如果我尝试不存在的文件,则myfile.good()再次返回true。如果我启动程序并首先尝试一个不存在的文件then myfile.good()返回false。

我不知道为什么输入有效文件后myfile.good()会继续返回true。

1 个答案:

答案 0 :(得分:2)

您要检查的是:

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;
}

好():

  

检查流是否已准备好输入/输出   操作,存在其他成员函数以检查特定状态   流(所有这些都返回bool值)

它检查状态标志。

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

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();
}

This了解详情。