![](/img/trans.png)
[英]Am I able to to use a string variable for a file name with fstream? C++
[英]C++ I can't use an fstream variable to save to a file
誰能在這里認識到使用fstream變量fFile的錯誤? 因為在函數Save()中(通過函數WriteTo())寫入磁盤進程始終失敗。 但是,如果我聲明新的本地fstream變量而不是fFile,則可以保存。 (請參閱下面的代碼的一部分)
謝謝
class CardCollection{
public:
CardCollection();
int Open(const char filename[]);
void Close();
void Close();
int NumCards()const;
void ReportStatus()const;
void AddCards();
void DeleteCard(int cardnum);
void ShowCard(int cardnum)const;
void ChangeCard(int cardnum);
void DoFind();
void DoFindAgain();
void DoView();
private:
int GetField(int anyallowed);
void Load();
int fNumCards;
char *fFileName;
std::fstream fFile;
DynamicArray fStore;
char *fFindString;
int fFindPos;
int fSearchField;
};
int CardCollection::Open(const char filename[])
{
//Keep copy of filename
fFileName = new char[strlen(filename)+1];
strcpy(fFileName, filename);
fFile.open(fFileName, std::ios::out | std::ios::in);
if(!fFile.good())
return -1;
Load();
return 0;
}
void CardCollection::Save()
{
for(int i = fNumCards ; i > 0; i--){
RefCard *r = (RefCard*) fStore.Nth(i);
r->WriteTo(fFile); // If I declare a new fstream here
// instead of using fFile, save is ok
}
if(fFile.good()){
std::cout << "Saving completed";
}
else{
std::cout << "Saving error";
}
}
我敢打賭,加載數據后,您不必重置fstream
。
將此添加到“保存”的開頭
fFile.clear();
fFile.seekp(0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.