0

I'm trying to write a simple program that will print the contents of a text file one line at a time. However, whenever I run the program i just get a blank screen. I'm certain the file I am trying to read contains text over several lines. Any help as to why this isn't working would be super helpfull.

bool show() {
    string line;
    ifstream myfile;
    myfile.open("tasks.txt", ios::app);
    while (!myfile.eof()) {
        getline (myfile, line);
        cout << line << endl;
    }
    myfile.close();
    return true;
}
4

2 に答える 2

1

(入力ストリーム)を使用ios::appしていることが問題である可能性がありますが、これは意味がありません。ifstream

これによると、

ios::app:すべての出力操作はファイルの最後で実行され、コンテンツがファイルの現在のコンテンツに追加されます。This flag can only be used in streams open for output-only operations.

これを試して:

std::string line;
ifstream myfile ("tasks.txt");
if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {
        std::cout << line << std::endl;
    }
    myfile.close();
}
于 2013-09-20T14:36:26.210 に答える
0

の戻り値を確認しましたmyfile.isopen()か? ファイルが存在しないか、読み取り権限がない可能性があります。

そうそう、私はそれを逃しました - 追加フラグ。する必要がありますios::in

于 2013-09-20T14:46:16.067 に答える