64,282
社区成员
发帖
与我相关
我的任务
分享
struct cashier
{
int cashierNumber;
int password;
};
vector <cashier> account;
cashier _cashier;
cin>>_cashier.cashierNumber; //?需要重载吗。
cin>>_cashier.password;
//注册账户
void reg()
{
ofstream new_file("d:\\rootNumber.txt",ios::app);
if (!new_file){cout << "打开文件失败!";}
cout << "输入新账号:";
cin>>_cashier.cashierNumber;
cout <<"输入密码:";
cin>>_cashier.password;
account.push_back(_cashier);
//对于注册来说,你有没有考虑过对于新账号与密码的挑剔准则呢?比如你的QQ账号是不能重复的,而且QQ还是 //动生成的,当然在这里你可以不用自动生成的,但是最起码账号得是不能重复的吧,还有密码的字符数与字符集 //有考虑吗?最长多少最短多少,哪些字符时合法的,哪些是不合法的?大概能想到的就这么多了,你已经做得可 //以了,但是好东西都是尽善尽美一点一点做出来的。
//还有,你下面的代码可以不用的,直接new_file<<cashier就行了(前提是得重载cashier的输出文件流)
for (it=(account.begin()+account.size()-1);it!=account.end();it++)
{
new_file<<it->cashierNumber<<" ";
new_file<<it->password<<endl;
}
new_file.close();
cout<<"注册成功!";
}
//注册账户
void reg()
{
ofstream new_file("d:\\rootNumber.txt",ios::app);
if (!new_file){cout << "打开文件失败!";}
cout << "输入新账号:";
cin>>_cashier.cashierNumber;
cout <<"输入密码:";
cin>>_cashier.password;
account.push_back(_cashier);
for (it=(account.begin()+account.size()-1);it!=account.end();it++)
{
new_file<<it->cashierNumber<<" ";
new_file<<it->password<<endl;
}
new_file.close();
cout<<"注册成功!";
}
谢谢
void main()
{
ofstream root_file;
root_file.open("d:\\rootNumber.txt ",ios::out);
if (!root_file)
{
cout<< "创建根账户失败!"<<endl;
}
_cashier.cashierNumber="888888";
_cashier.password="888888";
account.push_back(_cashier);
for (vector<cashier>::iterator it=account.begin();
it!=account.end();it++)
{
root_file<<it->cashierNumber<<" ";
root_file<<it->password;
}
root_file.close();
system("pause");
}
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct cashier
{
int cashierNumber;
int password;
//如果是把整个cashier对象交给流对象的话,那他就不识别了,因为cashier是自定义类型,需要重载
//默认的还是public
//例外流对象的重载函数只能声明为friend形式
friend ofstream& operator<< (ofstream &out, const cashier &c)
{
out<<c.cashierNumber<<" "<<c.password;
return out;
}
friend ifstream& operator>> (ifstream &in, cashier &c)
{
in>>c.cashierNumber>>c.password;
return in;
}
};
void main()
{
vector<cashier> account;
cashier temp;
cin>>temp.cashierNumber>>temp.password;
//cashier是一个结构体,默认的权限是public,所以可是通过对象直接获取成员变量
//成员变量都是基本内置类型,cin与cout都已经在std中事先重载好了,不需要用户重载了
cout<<temp.cashierNumber<<" "<<temp.password<<endl;
//关于如何在数组account中增加元素,这是vector的简单使用,你看看vector的使用介绍就行了。
account.push_back(temp);//push_back()的参数是vector<T>里面的T类型,虽然支持隐式转换,但最好不要
//下面是从文件读取一系列的数据,放入account中
ifstream in("b.txt");
if (!in)
{
cout<<"open file fail"<<endl;
}
cashier ctemp;
while (!in.eof())
{
in>>ctemp; //使用到了重载的文件输入流
account.push_back(ctemp);
}
//下面是将account中的数据放到文件中
ofstream out("writefile.txt");//假如没有这个文件,编译器根据语法就会创建一个出来
//如果找不到文件就打开失败要这么写 ofstream out("writefile.txt",ios::_Nocreate);
//这里使用找不到就自行创建一个的形式
vector<cashier>::const_iterator it = account.begin();
for (; it != account.end(); ++it)
{
out<<*it<<endl;
}
//在工程目录下会出现一个writefile.txt的文件,里面的内容为
//111 222
//12301 1111
//12302 2222
//12303 3333
//12304 4444
}