做练习题
struct emp
{
int num;
string name;
int age;
float wage;
};
int main()
{
emp s[7]= { 2101,"Li",34,1203,2104,"Wang",23,674.5,2108,"Fun",54,778,
3006,"Xue",45,476.5,5101,"Ling",39,656.6 },s1;
//ofstream outfile("staf.dat");
fstream iofile("staf.dat", ios::in | ios::out | ios::binary);
//iofile.clear();
if(!iofile)
{
cerr << "open staff.dat error!";
abort();
}
int i, m, num;
cout << "Five staff:" << endl;
for (i = 0; i < 5; i++)
{
cout << s[i].num << ' ' << s[i].name << ' ' << s[i].age << ' ' << s[i].wage << endl;
iofile.write((char*)&s[i], sizeof(s[i]));
}
cout << "please input data you want insert:" << endl;
for(i=0;i<2;i++)
{
cin >> s1.num >> s1.name >> s1.age >> s1.wage;
iofile.seekp(0, ios::end);
iofile.write((char*)&s1, sizeof(s1));
}
iofile.seekp(0, ios::beg);
for (i = 0; i < 7; i++)
{
iofile.read((char*)&s[i], sizeof(s[i]));
cout<< s[i].num << ' ' << s[i].name << ' ' << s[i].age << ' ' << s[i].wage << endl;
}
bool find;
cout << "enter number you want search,enter 0 to stop.";
cin >> num;
while (num)
{
find = false;
iofile.seekg(0, ios::beg);
for (i = 0; i < 7; i++)
{
iofile.read((char*)&s[i], sizeof(s[i]));
if (num == s[i].num)
{
m = iofile.tellg();
cout << num << " is No." << i << endl;
cout << s[i].num << " " << s[i].name << " " << s[i].age << " " << s[i].wage << endl;
find = true;
break;
}
}
if (!find)
cout << "can't find " << num << endl;
cout << "enter number you want search,enter 0 to stop.";
cin >> num;
}
iofile.close();
return 0;
}
Debug error!
刚开始用了clear,不报错了,但是写不了文件,文件依然没有建立。
后来建立文件之后就好了
这个跟| ios::binary没啥关系吧,加了 ios::in就不会自动创建新文件了