在对象数组中搜索操作?

时间:2016-05-11 16:36:06

标签: c++ class

我正在制作简单的银行计划,我的班级名称是银行

它包含以下函数deposit()withdraw()show()getname()getbalance(),默认构造函数和参数构造函数。

我试图通过名称和余额在主程序中进行搜索操作。 但是,它没有显示输入的相应名称或余额的信息,而是显示了帐户持有者的完整信息列表。

请帮助解决此问题。

#include<iostream.h>
#include<string.h>

class bank
{
   char name[20],acNo[20],typeOfAc[10];
   double balance;
   public:
   bank()
   {
      strcpy(name,"NULL");
      strcpy(acNo,"XXXX");
      strcpy(typeOfAc,"XXXX");
      balance=0;
   }
   bank(char nm[20],char acn[20],char tac[10])
   {
      strcpy(name,nm);
      strcpy(acNo,acn);
      strcpy(typeOfAc,tac);
      balance=0;
   }

   double getbalance(){return balance;}
   char* getname(){return name;}
   void enter();
   void deposit();
   void withdraw();
   void show();
};

void bank::deposit()
{
   double d;
   cout<<"\nEnter Amount To deposit:";
   cin>>d;
   cout<<"\n";
   balance=balance+d;
   cout<<"\nSuccessful Deposit.\n";
}
void bank::withdraw()
{
   double w;
   cout<<"\nEnter amount to withdraw:";
   cin>>w;
   cout<<"\n";
   if((balance-w)<0)
   {
      cout<<"\nCan't withdraw!!";
      cout<<"\nYour Balance:"<<getbalance();
      return;
   }
   else
      balance=balance-w;
   cout<<"\nWithdrawal Successful.\n";
}
void bank::show()
{
   cout<<"\nName:"<<getname();
   cout<<"\nBalance:"<<getbalance();
}
void bank::enter()
{
   cout<<"\nPlease enter the following info\n";
   fflush(stdin);
   cout<<"\nName:";
   gets(name);
   cout<<"\n";
   cout<<"\nACcount Number:";
   gets(acNo);
   cout<<"\n";
   cout<<"\nType of Account:";
   gets(typeOfAc);
   cout<<"\n";
}

int main()
{
   int i;
   double b1;
   char n[20],nn[20];
   bank b[10];
   for(i=0;i<3;i++)
   {
      b[i].enter();
      b[i].deposit();
   }
   //search by name
   cout<<"\nEnter the name for search by name:";
   fflush(stdin);
   gets(n);
   for(i=0;i<3;i++)
   {
      strcpy(nn,b[i].getname());
      if(strcmp(nn,n)==0);
      b[i].show();
   }
   cout<<"\nEnter the balance for search by balance:";
   cin>>b1;
   for(i=0;i<3;i++)
   {
      if(b[i].getbalance()==b1);
      b[i].show();
   }
   return 0;
}

2 个答案:

答案 0 :(得分:4)

if(strcmp(nn,n)==0);
b[i].show();

if(b[i].getbalance()==b1);
b[i].show();

它是每个第一行的; ......将其变为空的if条件。第二行与if无关,并且始终运行。这是您应该始终对每个if语句使用花括号的原因之一,即使它只有一行。

答案 1 :(得分:2)

你有非常混乱的C和C ++。我会做一个纯C ++类声明,就像这个

class bank {
    string name, acNo, typeOfAc;
    double balance;
public:
    bank(string nm = "NULL", string acn = "XXXX", string tac = "XXXX")
        : name(nm), acNo(acn), typeOfAc(tac), balance(0) {}

    double getbalance() { return balance; }
    string getname() { return name; }
    . . .
};

此处stringstd::string

而不是

char n[20];
fflush(stdin);
gets(n);    // unsafe

应该是

string n;
cin >> n;

,以及更正您的搜索

if (b[i].getname() == n)    // no semicolon here
    b[i].show();