1

我在 fstream 位于特定位置时无法写入我的文件时遇到问题。在下面的代码中,当注释行被取消注释时,文件被写入,但是当它被注释时,文件根本没有被写入。我添加了一堆控制台输出,它表示“outputFile << newWord << endl;”周围的两个输出 已完成,但从未实际写入该文件。

void write_index( string newWord )
{
fstream outputFile( "H:\\newword.txt", ios::app );
int same = 0;
string currWord;
currWord.resize(5);
//outputFile << newWord << endl;
while( !outputFile.eof() )
{
    getline( outputFile, currWord );
    cout << "Checking if " << newWord << "is the same as " << currWord << endl;
    if( newWord == currWord )
    {
        cout << "It is the same" << endl;
        same = 1;
        break;
    }
}
if( same != 1 )
{
    cout << "Writing " << newWord << "to file" << endl;
    outputFile << newWord << endl;
    cout << "Done writing" << endl;
}
outputFile.close();

}

4

1 回答 1

2

我有点相信你正在寻找这些方面的东西:

void write_index( const string& newWord )
{
    fstream outputFile( "H:\\newword.txt", ios::in);
    bool same = false;

    if (outputFile)
    {
        string currWord;
        while (getline(outputFile, currWord))
        {
            cout << "Checking if " << newWord << " is the same as " << currWord << endl;
            same = (newWord == currWord);
            if (same)
            {
                cout << "It is the same" << endl;
                break;
            }
        }
    }

    if (!same)
    {
        outputFile.close();
        outputFile.open("H:\\newword.txt", ios::app);

        cout << "Writing " << newWord << "to file" << endl;
        outputFile << newWord << endl;
        cout << "Done writing" << endl;
    }

    outputFile.close();
}

有更好的方法可以做到这一点,但这可能是一个不错的起点。

于 2013-02-27T02:55:33.387 回答