我試圖用這段代碼從文件中讀取數據並將其存儲在向量中。這工作一次並正確顯示一切。C++爲什麼我的文件在我重新啓動程序時被截斷?
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! ";
}
一切工作正常,但即使該文件將擦拭,並沒有任何在它一旦我完成這個項目,我試圖追加到該文件。爲了清楚起見,我需要以前的內容,並且每次重新打開程序時添加的新行都在那裏。
myFile.flush(); – KonstantinL
@KonstantinL'ofstream'關閉破壞並關閉時刷新。 –
擦除整個文件並沒有什麼意義。考慮一下你可能正在查看錯誤的文件,當你不使用完整路徑名並依賴於默認工作目錄時,這是一個長期的問題。 –