c语言读取顺序文件并处理
我们今天学习如何在创建读取文件之后,对其进行处理!不妨看看c语言如何读取顺序文件并处理,以下仅供参考!
以下是代码:
# include
# include
# include
# include
# include
using namespace std;
enum requesttype{ZERO_BALANCE=1,CREDIT_BALANCE, DEBIT_BANLANCE,END};//这里定义的是枚举类型,也就是赋值1,2,3
int getrequest();
bool shoulddisplay(int, double);//这个函数的`作用,就是从读取的数据中选择不同的条件进行输出!
void outputline(int, const string, double);//输出数据
int main() {
ifstream inclientfile("clients.dat", ios::in);//我们假定已经定义好了相关的数据在文件clients.dat中!
if (!inclientfile) {
cerr << "file could not be opened" << endl;
exit(1);
}
int request;
int account;
char name[30];
double balance;
request = getrequest();
while (request != END) {//选择数据类型
switch (request) {
case ZERO_BALANCE:
cout << "
accounts with zero balances:
";
break;
case CREDIT_BALANCE:
cout << "
accounts with creadit balances:
";
break;
case DEBIT_BANLANCE:
cout << "
accounts with debit balances:
";
break;
}
inclientfile >> account >> name >> balance;//读入数据
while (!inclientfile.eof()) {//设置循环条件
if (shoulddisplay(request, balance)) {
outputline(account, name, balance);
}
inclientfile >> account >> name >> balance;
}
inclientfile.clear();
inclientfile.seekg(0);//回到文件的起始位置
request = getrequest();
}
cout << "end of run." << endl;
system("pause");
return 0;
}
int getrequest() {
int request;
cout << "
enter request" << endl
<< "1-list accounts with zero balances" << endl
<< "2-list accounts with credit balances" << endl
<< "3-list accounts with debit balances" << endl
<< "4-end of run" << fixed << showpoint;
do {
cout << "
?";
cin >> request;
} while (requestEND);
return request;
}
bool shoulddisplay(int type, double balance) {
if (type == ZERO_BALANCE&&balance == 0) {
return true;
}
if (type == CREDIT_BALANCE&&balance < 0) {
return true;
}
if (type == DEBIT_BANLANCE&&balance > 0) {
return true;
}
return false;
}
void outputline(int account, const string name, double balance) {
cout << left << setw(10) << account << setw(13) << name
<< setw(7) << setprecision(2) << right << balance << endl;
}
以下是执行后结果:
【c语言读取顺序文件并处理】相关文章: