如何在这个c++程序中创建一个搜索函数
How to create a search function in this C++ program
我正在用命令行界面编写一个小程序。在这个程序中,我想要创建一个搜索函数。
但是它用于字符搜索的名字,但我想创建相同的函数,将能够搜索使用"学生注册号"。
我遇到问题的搜索案例:
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))){
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针