当用户尝试搜索数据文件中不可用的内容时,如何使用 cout
向用户输出消息?我尝试了以下代码:
cin>>temp;
fstream a;
a.open("Account.dat",ios::app|ios::in|ios::out);
while(a>>acno>>type>>cid>>credit>>debit>>tellid){
if(temp==acno){
cout<<"Customer ID : "<<cid<<endl;
break;
}//if not found , display an error message,I've tried using else block here
}
谢谢!
最佳答案
您不能在循环中使用 if - else
,因为每次读取帐户与搜索条件不匹配时都会执行此操作。相反,使用一个变量来跟踪我们是否找到了一些东西:
cin>>temp;
fstream a;
a.open("Account.dat",ios::app|ios::in|ios::out);
bool found = false;
while(a>>acno>>type>>cid>>credit>>debit>>tellid){
if(temp==acno){
cout<<"Customer ID : "<<cid<<endl;
found = true;
break;
}
}
if(!found) {
// display error message and exit
}
顺便说一句,这不是 iostream 的目的。相反,使用像 Boost.PropertyTree 这样的库来保存数据。这将大大简化您的代码。
关于C++ 文件处理,如何实现在此代码中找不到的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38294486/