求C++高手解决一文件操作的问题:

plovej 2005-04-18 11:33:31
用C++写一段代码:
#include<iostream.h>
#include<fstream.h>
#include<string.h>
class book
{
private:
int code;
char name[20];
public:
void setcode(int i)
{
code=i;
}
int getcode()
{
return code;
}
void setname(char*s)
{
strcpy(name,s);
}
};

void main()
{
book b1;
char flag; // 用于判断循环
fstream file;
file.open("book.txt",ios::app);// 打开文件,如果不存在则新建一个;
do
{//请在此处添加代码:(要求如下):
// 程序在运行时用户,首先显示出书的编号code(注意:如果开始文件是空的,
// 则自动显示为1);
// 然后提示用户输入书名,敲回车后把b1写入文件;
// 选择'y'后继续输入,则code 变为2,以后每次都加1....(问题关键)!
cout<<"你是否要继续?(y/n):";
cin>>flag;
}while(flag=='y'||flag=='Y');
}

...全文
134 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
juan2001 2005-04-18
  • 打赏
  • 举报
回复
#include<iostream.h>
#include<fstream.h>
#include<string.h>
class book
{
private:
int code;
char name[20];
public:
void setcode(int i)
{
code=i;
}
int getcode()
{
return code;
}
void setname(char*s)
{
strcpy(name,s);
}
};

void main()
{
book b1;
char flag; // 用于判断循环
fstream file;
file.open("book.txt",ios::app);// 打开文件,如果不存在则新建一个;
do
{
if(文件==0)
{
code=0;
cout<<"请输入书名号:";
cin>>“书名号”;
code++;//为空时再这里加1,如果不想让输入书名号,动作算一次操作,删除此行
break;
}
cout<<"book:"<<code;
//请在此处添加代码:(要求如下):
// 程序在运行时用户,首先显示出书的编号code(注意:如果开始文件是空的,
// 则自动显示为1);
// 然后提示用户输入书名,敲回车后把b1写入文件;
// 选择'y'后继续输入,则code 变为2,以后每次都加1....(问题关键)!
cout<<"你是否要继续?(y/n):";
cin>>flag;
code++;// 不为空时在这里加1
}while(flag=='y'||flag=='Y');
}


dui对你的程序不熟,只写了你要的部分,其他用汉字代替,请谅解。。。。
lw1a2 2005-04-18
  • 打赏
  • 举报
回复
sorry,看错了
lw1a2 2005-04-18
  • 打赏
  • 举报
回复
BS这个题,code 竟然不用静态的
plovej 2005-04-18
  • 打赏
  • 举报
回复
小弟感激不尽,多谢了!
以后多多指教,本人刚学C++。
jjduan185 2005-04-18
  • 打赏
  • 举报
回复
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
struct book
{
string name;
int code;
};
void main()
{

ifstream in("book.txt");
if(!in)
{
cout<<"File open failed!\n";
exit(1);
}
int counter(0);
book b1;
vector<book> bv;
while(in>>b1.code && in>>b1.name)
{
bv.push_back(b1);
counter++;
}
in.close();
bool flag=true;
while(flag)
{
cout<<(counter+1)<<endl;
cout<<"Input name for book "<<counter+1<<": ";
cin>>b1.name;
b1.code=++counter;
bv.push_back(b1);
cout<<"Do you want to continue ? < Y/N > ";
char f;
cin>>f;
if(f=='y' || f=='Y') flag=true;
else flag=false;
}
ofstream in1("book.txt");
if(!in1)
{
cout<<"Open Failed\n";
exit(1);
}
for(int i=0;i<bv.size();i++)
{
in1<<bv[i].code<<" ";
in1<<bv[i].name<<endl;
}
in1.close();
}
方法笨了点,但很实用,也很容易看懂 ,你看行不?

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧