gpt4 book ai didi

c++ - fstream 不写入文件

转载 作者:行者123 更新时间:2023-11-30 04:20:43 28 4
gpt4 key购买 nike

当文件位于特定位置时,我遇到了 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();

最佳答案

我相信您正在寻找类似的东西:

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

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

关于c++ - fstream 不写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15103209/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com