我正在尝试使用此代码从文件中读取并将值存储在 vector 中。这只工作一次并正确显示所有内容。
void SongList::LoadSongsFromFile()
{
song temp;
string line;
ifstream myFile("SongListFile.txt");
while (getline(myFile, line)) {
myFile >> temp.title;
myFile >> temp.artist;
myFile >> temp.genre;
songs.push_back(temp);
}
}
然后我想附加到文件中,使用以下内容:
void SongList::AddSong(song tmp)
{
cout << "Enter the title, artist then genre of the song, each on a new line.\n";
cin >> tmp.title;
cin >> tmp.artist;
cin >> tmp.genre;
songs.push_back(tmp);
ofstream myFile("SongListFile.txt");
myFile.open("SongListFile.txt", ios::app);
myFile << tmp.title << " " << tmp.artist << " " << tmp.genre;
cout << tmp.title << " by " << tmp.artist << " is now a part of the song library! ";
}
一切正常,但一旦我完成程序,文件将被删除并且没有任何内容,即使我试图附加到文件。明确地说,每次重新打开程序时,我都需要以前的内容和添加的新行。
最佳答案
std::ofstream myFile("SongListFile.txt");
打开文件并截断。你应该使用 std::ofstream myFile("SongListFile.txt", std::ios::app);
否则,您可以使用 std::ofstream myFile;
声明 myFile 对象,然后使用它和附加选项打开一个文件:myFile.open("SongListFile.txt", std::ios::app);
关于C++ 为什么我的文件在我重新启动程序时被截断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43413471/