输入数据保存后正常关闭程序,再打开文件数据却没有被保存进去。
# include <iostream>
# include <fstream>
# include <string.h>
#include <conio.h>//用getch();
using namespace std;
class book
{
public:
string book_id;
string book_name;
string author;
string publishing;
double price;
book* Next;
void Input()
{
cout << "请输入书籍编号:"; cin >> book_id;
cout << "请输入书籍名称:"; cin >> book_name;
cout << "请输入作者:"; cin >> author;
cout << "请输入出版社:"; cin >> publishing;
cout << "请输入定价:"; cin >> price;
}
void ReadFile(istream& in)
{
in >> book_id >> book_name >> author >> publishing >> price;
}
void Show()
{
cout << "编号:" << book_id << "\t" << "名称:" << book_name << "\t" << "作者:" << author << "\t"
<< "出版社:" << publishing << "\t" << "定价:" << price << endl;
}
};
class Manage
{
public:
Manage();
~Manage();
void ShowMenu();//展示菜单
void Find();
void Save();
void AddItem()
{
End->Input();
End->Next = new book;
End = End->Next;
cout << "添加成功!" << endl;
cout << "输入任意字符!继续……";
getch();
Save();
}
private:
book* Head, * End;
ifstream in;
ofstream out;
book* FindID(string id)
{
for (book* p = Head; p->Next != End; p = p->Next)//匹配成功则返回上一个指针,不成功就返回空
if (p->Next->book_id==id)return p;
return NULL;
}
};
Manage::Manage()
{
Head = new book;
Head->Next = new book;
End = Head->Next;
in.open("book.txt");
if (!in)
cout << "这是一个新系统,无信息。请先输入。" << endl;
else
{
while (!in.eof())
{
End->ReadFile(in);
if (End->book_id.empty())break;//string字符串为空
End->Next = new book;
End = End->Next;
}
in.close();
cout << "\t\t读取信息成功!" << endl;
}
}
Manage::~Manage()
{
Save();
for (book* temp; Head->Next != End;)
{
temp = Head->Next;
Head->Next = Head->Next->Next;
delete temp;
}
delete Head, End;
}
void Manage::ShowMenu()
{
cout << " ▏------------------------ ▏" << endl;
cout << " ▏ 1.添加图书 ▏" << endl;
cout << " ▏ 2.查找图书 ▏" << endl;
cout << " ▏ 0.退出管理系统 ▏" << endl;
cout << " --------------------------------------------------- " << endl;
cout << "请选择:";
}
void Manage::Find()
{
string id;
book* p = NULL;
cout << "请输入要查找的图书的编号:"; cin >> id;
if (p = FindID(id))
{
p->Next->Show();
cout << "输入任意字符!继续……";
getch();
}
else
{
cout << "没有找到该书!" << '\n' << endl;
cout << "输入任意字符!继续……";
getch();
}
}
void Manage::Save()
{
out.open("book.txt");
for (book* p = Head->Next; p->Next != End; p = p->Next)
out << p->book_id << "\t" << p->book_name << "\t" << p->author << "\t"
<< p->publishing << "\t" << p->price << '\n';
out.close();
}
int main()
{
int x, i = 0;
bool quit = false;
Manage AA;
while (!quit)
{
system("cls");
AA.ShowMenu();
cin >> x;
switch (x)
{
case 0:quit = true; break;
case 1:AA.AddItem(); break;
case 2:AA.Find(); break;
}
}
return 0;
}
如何才能保存到文件当中呢?
保存的文件路径或文件名不对
保存时打开文件的模式不对
保存时写入数据的格式不对
保存完没有关闭文件
……
你的open函数都没有传入操作方式,写什么文件啊
你总要告诉程序,到底是要读文件还是写文件啊
你不传参数,默认就是读