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

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

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

相关文章:

c++ - 无法构造对象

c++ - 为什么 std::bitset 不带有迭代器?

c++ - 正确继承std::string的方法是什么?

c++ - 在 C++ 中原则上不可能进行严格的模板评估吗?

c++ - 传递给 std::sort 时,全局函数比仿函数或 lambda 慢

c - 如何在c中搜索文本文件中的特定字符串

c - 如何检测文件中是否存在数据 C 文件处理

c - 从文件中读取,但我无法打印最后一行?

c++ - 从真值的 STL vector 中随机选择索引

c++ - 如何使用 Visual Studio CppUnitTestFramework 访问我的代码