如何在这个c++程序中创建一个搜索函数

How to create a search function in this C++ program

本文关键字:一个 函数 搜索 创建 c++ 程序      更新时间:2023-10-16

我正在用命令行界面编写一个小程序。在这个程序中,我想要创建一个搜索函数。

但是它用于字符搜索的名字,但我想创建相同的函数,将能够搜索使用"学生注册号"。

我遇到问题的搜索案例:

int kWord;
stdDetails  stdFind;
cout<<"Enter the Student Registration Number of the Student: ";
cin>>kWord;
for(int x=0;x<i;x++){
  stdFind = stdDetailsStructs_0[x];
  if(!strcmp(kWord,stdFind.stdNum)){
    search=1;
    break;
  }
}
if(search==1){
  display(stdFind);
}else{
  cout<<"Student details not found please try again."<<endl;
}

我不认为kWord应该是int,因为学生注册号应该是字符串。如果它们是数字,您应该使用==来检查相等性。

search在哪里声明?

如果是全局变量,应该有

if(search==1){
  display(stdFind);
}else{
  cout<<"Student details not found please try again."<<endl;
  search = 0; // <-- add this
}

stdNum是stdDetails结构体中的int类型。所以使用==操作符代替strcmp()

                    int kWord;
                    cout<<"Enter the Student Registration Number of the Student: ";
                    cin>>kWord;
                        for(int x=0;x<i;x++){
                        if(kWord==stdDetailsStructs_0[x].stdNum)                       
                        {
                            search=1;
                            break;
                         }   
                        }
                        if(search==1){
                            display(stdFind);
                        }else{
                            cout<<"Student details not found please try again."<<endl;
                        }

如果它只是一个数字,为什么不能使用==运算符而不是strcmp

使用——如果(kWord = = stdFind.stdNum)…strcmp()用于字符串比较。kWord和stdNum为整数值

我会使用strncmp()(即使它真的是C风格,你可以使用STL),因为它可能一直失败,因为'n'在行尾。

如果stdNum实际上是一个字符串:

if(!strncmp(kWord,stdFind.stdNum, strlen(stdFind.stdNum))){