4

これらの行は、main() の唯一の内容です:

fstream file = fstream("test.txt", ios_base::in | ios_base::out);
string word;
while (file >> word) { cout << word + " "; }
file.seekp(ios::beg);
file << "testing";
file.close();

プログラムはファイルの内容 (「怒っている犬」) を正しく出力しますが、後でファイルを開くと、期待どおりの「テスト用の犬」ではなく、「怒っている犬」と表示されます。

完全なプログラム:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    fstream file = fstream("test.txt", ios_base::in | ios_base::out);
    string word;
    while (file >> word) { cout << word + " "; }
    file.seekp(ios::beg);
    file << "testing";
    file.close();
}
4

1 に答える 1

8

コードに 2 つのバグがあります。

まず、iostreamコピー コンストラクターがないため、(厳密に言えば) 自分fileのやり方で初期化することはできません。

第 2 に、ファイルの最後まで実行すると、eofbitが設定され、ストリームを再び使用する前にそのフラグをクリアする必要があります。

fstream file("test.txt", ios_base::in | ios_base::out);
string word;
while (file >> word) { cout << word + " "; }
file.clear();
file.seekp(ios::beg);
file << "testing";
file.close();
于 2012-08-11T15:52:36.217 に答える