传递一组对象进行搜索

时间:2016-04-03 12:20:41

标签: c++ search

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class student
{ int rno;
  char name[20];
  float total;
  public:
  void In();
  void Out();
  void search(student ob[50],int,int);
  int retrno()
  { return rno;               //returns the roll no of student 
  }
};
void student::search(student ob[],int n,int srno)
{ int flag=0;
  for(int i=0;i<n;++i)
     if(ob[i].retrno()==srno)     //checking for rollno match
       { flag=1;
         cout<<"Student found";
         ob[i].Out();                 //calling Out() when match is found
       }
   if(flag==0)
   cout<<"No matching records";
}
void student::In()
{ cout<<"Enter rno:";
  cin>>rno;
  cout<<"Enter name:";
  gets(name);
  cout<<"Enter total:";
  cin>>total;
}
void student::Out()
{ cout<<"rno:";
  cout<<rno;
  cout<<"Name:";
  puts(name);
  cout<<"Total:";
  cout<<total;
}
void main()
{ student ob[50];
  int n,srno;
  cout<<"Enter no. of students:";
  cin>>n;
  for(int i=0;i<n;++i)
       ob[i].In();                    //In() is called n times
  cout<<"Enter rno to be searched:";
  cin>>srno;
  ob.search(ob,n,srno);
 }

编译时我得到2个错误。

11: Undefined structure 'student'

52: Structure required on left side of . or .*

我试着看看函数原型是否有错,但它看起来很好。我厌倦了没有数组大小的原型并获得了同样的错误。我也尝试在全局范围内初始化类,但是遇到了同样的错误(我的想法用完了)。 请帮我找出问题所在。

1 个答案:

答案 0 :(得分:0)

您的student课程代表一个学生,我认为搜索功能不是其中的一员更好,考虑到您也传递了一系列学生:

void search(student ob[], int n, int srno)
{
    // ... keep your implementation
}

然后你可以用:

来调用它
search(ob,n,srno);

将输出部分分开并使搜索功能仅返回索引或指向找到的元素的指针(或不是),这样会更好。

我同意Ulrich Eckhardt关于所包含的图书馆的信息。

我补充说,您应该以某种方式检查用户输入的内容,并且我想记住使用起来更正确:

int main() {
    // ... stuff...
    return 0;
}