1

I need the user to enter a file and for as long as the user enters files that exist the file will loop. The program will break when the user enters a file that does not exist.

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

when i enter a file that exists, myfile.good() returns good then if i try a file that does not exist the like myfile.good() returns true again. If i start the program and i try first a file that does not exist then myfile.good() returns false.

I do not know why after i enter a valid file myfile.good() will continue to return true.

4

1 回答 1

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

好的() :

检查流是否准备好进行输入/输出操作,存在其他成员函数来检查流的特定状态(它们都返回布尔值)

它检查状态标志。

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

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

了解更多详情。

于 2013-06-12T00:18:43.077 回答