【问题标题】:C++ File Handling , How to implement record not found on this codeC++ 文件处理,如何实现在此代码上找不到记录
【发布时间】:2016-07-10 17:14:21
【问题描述】:

当用户尝试搜索数据文件中不可用的内容时,如何使用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
        }

谢谢!

【问题讨论】:

  • 5您添加了C标签是因为它们以相同的字母开头?不要垃圾邮件无关语言的标签!
  • 那么为什么else 不起作用?
  • FiestStep - 它只返回第一条记录的结果
  • @Olaf 没有 C 标签。
  • @Olaf - c 和 c++ 不相关? :D

标签: c++ c++11 file-handling


【解决方案1】:

您不能在循环中使用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
}

顺便说一句,这不是 iostreams 的用途。相反,使用像 Boost.PropertyTree 这样的库来保存数据。这将大大简化您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多