我刚学文件操作这方面的知识,被输入输出方式搞晕了,大家能帮我看看吗?
我想用C++做个图书管理系统,为每个读者创建一个文件,文件里面有所借书本的数目和具体的信息(现在只写到借书的函数,但一直没办法按自己的想法实现)。文件开始给出书本的数目,接下去是具体的信息。把新借的书本的具体信息添加到文件后面,新的书本数目覆盖原来借的书本数目。ios::app和ios::ate,这两种方式有什么区别吗?开始学文件的知识,就被这个问题卡住了。第一次来CSDN提问题,大家能帮我看看什么原因出错吗?
#include <iostream>
#include <conio.h>
#include <iomanip>
#include <fstream>
using namespace std;
class reader;
class book
{ protected:
string bookname;
string booknumber;
string author;
public:
friend class reader;
};
class reader
{ public:
reader()
{amount=0;}
void readerfile();
void borrow();
void giveback();
void show();
protected:
string readername;
char cardnumber[20];
int amount;
book books[5];
};
void reader::readerfile()
{ cout < <endl < < " 读者: "; cin> > readername;
cout < < " 卡号: "; cin> > cardnumber;
ifstream infile(cardnumber,ios::in);
if(!infile)
{ ofstream outfile(cardnumber,ios::out);
outfile < <amount;
outfile.close();
}
infile.close();
}
void reader::borrow()
{ clrscr();
ifstream infile(cardnumber,ios::in);
if(!infile)
{ cerr < <endl < < "无法打开文件! " < <endl;
exit(1);
}
infile> > amount;
infile.close();
ofstream outfile(cardnumber,ios::ate);
int num;
cout < <endl < <readername < < " " < <cardnumber;
if(amount==0) cout < < " 尚未借书! " < <endl;
if(amount!=0) cout < < " 已借 " < <amount < < "书! " < <endl;
cout < <endl < < "欲借书本数目:[ ]\b\b ";
cin> > num;
if((num <0)||(num> 5)||(num> 5-amount))
{ clrscr();
cout < <endl < < "输入错误!请重新输入! " < <endl < < "欲借书数目:[ ]\b\b ";
cin> > num;
}
if(num!=0)
{
amount=amount+num;
outfile.seekp(ios::beg);
outfile < <amount;
outfile.seekp(ios::end);
for(int i=0;i <num;i++)
{ cout < <endl;
cout < < "书名: ";cin> > books[i].bookname;
outfile < <endl < <books[i].bookname;
cout < < "编号: ";cin> > books[i].booknumber;
outfile < <endl < <books[i].booknumber;
cout < < "作者: ";cin> > books[i].author;
outfile < <endl < <books[i].author;
}
}
outfile.close();
}
int main()
{ int choice=1;
reader readers;
readers.readerfile();
while(choice)
{ clrscr();
cout < <endl < <endl < <endl < <endl < <endl < <endl;
cout < <setw(45) < < "=================== " < <endl;
cout < <setw(45) < < "| | " < <endl;
cout < <setw(45) < < "| 1.借书 | " < <endl;
cout < <setw(45) < < "| 2.还书 | " < <endl;
cout < <setw(45) < < "| 3.浏览 | " < <endl;
cout < <setw(45) < < "| 0.退出 | " < <endl;
cout < <setw(45) < < "| | " < <endl;
cout < <setw(45) < < "=================== " < <endl;
cout < <setw(45) < < " 请选择:[ ]\b\b ";
cin> > choice;
if(choice!=1&&choice!=2&&choice!=3&&choice!=0)
{
cout < < "请重新选择:[ ]\b\b ";
cin> > choice;
}
switch(choice)
{ case 1: readers.borrow(); break;
case 2:
case 3: break;
}
}
return 0;
}
[解决办法]
if(choice!=1&&choice!=2&&choice!=3&&choice!=0)
{
cout < < "请重新选择:[ ]\b\b ";
cin> > choice;
}
用while不要用if.
原来还没写完啊。一个读者一个文件,这种存储方法可能不太合理哦。
用ASCII码写文件的时候,输出各个数据中间要输出一些空格用来将不同的数据隔开,不然输出后文件里的数据会连成一片,再次读取文件的时候就分不清谁是谁了。不信自己用记事本看看输出后的文件内容是什么样子的。