C++文件处理,如何实现在此代码上找不到记录

C++ File Handling , How to implement record not found on this code

本文关键字:代码 记录 找不到 实现 处理 文件 何实现 C++      更新时间:2023-10-16

当用户尝试搜索数据文件中不可用的内容时,如何使用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 这样的库来保存数据。这将大大简化您的代码。