马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iostream>
#include <string>
#include<fstream>
#include<windows.h>
using namespace std;
struct Xinxi
{
long id;
string name;
char sex;
};
bool Start();
bool Write();
bool Luru();
bool Owrite(Xinxi *ptr);
int main()
{
cout << "首先,感谢小甲鱼老师提供思路." << endl;
char Panduan;
if(Start())
{
cout << "初始化成功" << endl;
}
else
{
cout << "初始化失败" << endl;
}
do
{
cout << "\n1 打印数据\n" << "2 录入数据\n" << "3 退出程序\n" << endl;
cin >> Panduan;
switch (Panduan)
{
case '1':
Write();
break;
case '2':
Luru();
break;
case '3':
return 0;
default:
cout << "输入错误" << endl;
break;
}
} while (Panduan != '3');
return 0;
}
bool Start()
{
char Xuanze;
fstream out;
out.open("数据.txt",ios::out|ios::in);
if (!out)
{
ofstream Create("数据.txt");//创建文件
Create << "1\tAlan\tm\n";
if (!Create)
{
Create.close();
}
Create.close();
out.open("数据.txt", ios::out | ios::in);
if (!out)
{
out.close();
return false;
}
}
bool Panduan = true;
char temp;
while (out.get(temp))
{
if (temp == '2' || temp == '3'||temp == '4'||temp == '5'||temp == '6'||temp == '7'||temp == '8'||temp == '9')
{
cout << "检测到文件中有新数据,是否保留?(Y/N)" << endl;
while (Panduan)
{
cin >> Xuanze;
if (Xuanze == 'y' || Xuanze == 'Y')
{
out.close();
return true;
}
else if (Xuanze == 'n' || Xuanze == 'N')
{
out.close();
out.open("数据.txt", ios::trunc | ios::out);
out << "01\tAlan\tm";
out.close();
return true;
}
else
{
cout << "输入有误,请重新输入" << endl;
}
}
}
}
out.close();
return true;
}
bool Write()
{
ifstream out;
out.open("数据.txt");
if (!out)
{
cout << "读取文件失败" << endl;
out.close();
return false;
}
else
{
cout << "\n正在输出记录数据...... ";
for (int i = 0; i <= 100; i++) // 打印百分比
{
std::cout.width(3);
std::cout << i << "%";
Sleep(5);
std::cout << "\b\b\b\b";
}
cout << "读取文件成功" << endl;
cout << "id\t" << "name\t" << "sex" << endl;
char temp;
while (out.get(temp))
{
cout << temp ;
}
cout << endl;
out.close();
return true;
}
}
bool Luru()
{
Xinxi Xdate, *pXdate = &Xdate;
cout << "录入初始化完成,当id输入-1时退出" << endl;
do
{
cout << "请输入Id: ";
cin >> Xdate.id;
while (Xdate.id < -1)
{
cin.clear();
cin.ignore(100, '\n');
cout << "输入有误,请输入Id: ";
cin >> Xdate.id;
}
if (Xdate.id == -1)
{
break;
}
cout << "请输入姓名:";
cin >> Xdate.name;
cout << "请输入性别:";
cin >> Xdate.sex;
while ((Xdate.sex != 'm') && (Xdate.sex != 'f') && (Xdate.sex != 'M') && (Xdate.sex != 'F'))
{
cout << "输入有误,请输入性别:";
cin.clear();
cin.ignore(100, '\n');
cin >> Xdate.sex;
}
if (Owrite(pXdate))
{
cout << "录入成功" << endl;
}
else
{
cout << "录入失败" << endl;
}
}
while (1);
return true;
}
bool Owrite(Xinxi *ptr)
{
fstream out("数据.txt", ios::app | ios::out);
if (!out)
{
out.close();
return false;
}
out << ptr->id << "\t";
out << ptr->name << "\t";
out << ptr->sex << "\n";
out.close();
return true;
}
|