如何从数组执行索引搜索
我试图对字符串执行索引搜索,它运行但问题是它只打印出 i[0] 这是我的第一个条目。如果我查找另一个条目,它不起作用。请帮忙.. void clist(字符串 fn[],字符串 ln[], int 大小);
int search_list(const string fn[],const string ln[], int size, string find);
int main(){
string search;
cout << "This program searches a list .\n";
const int total = 3;
string fn[total];
string ln[total];
clist(fn,ln, total);
cout << "Search contact:____ ";
cin >> search;
search_list(fn,ln, total, search);
return 0;
}
void clist(string fn[],string ln[], int size){
cout << "Enter " << size << " contact.\n";
for (int index = 0; index < size; index++)
cin >> fn[index] >> ln[index] ;
}
int search_list(const string fn[], const string ln[],int size, string search){
for(int i=0;i<size;i++){
if((fn[i] == search)&& (i < size)){
cout<<"Result found "<<fn[i]<<" "<<ln[i]<<endl;
break;
}
cout<<"no record found"<<endl;
break;
}
}
im trying to perform an index search for string, it runs but the problem is that it only prints out i[0] which is my first entry. if i lookup another entry it doesn't work. Please help..
void clist(string fn[],string ln[], int size);
int search_list(const string fn[],const string ln[], int size, string find);
int main(){
string search;
cout << "This program searches a list .\n";
const int total = 3;
string fn[total];
string ln[total];
clist(fn,ln, total);
cout << "Search contact:____ ";
cin >> search;
search_list(fn,ln, total, search);
return 0;
}
void clist(string fn[],string ln[], int size){
cout << "Enter " << size << " contact.\n";
for (int index = 0; index < size; index++)
cin >> fn[index] >> ln[index] ;
}
int search_list(const string fn[], const string ln[],int size, string search){
for(int i=0;i<size;i++){
if((fn[i] == search)&& (i < size)){
cout<<"Result found "<<fn[i]<<" "<<ln[i]<<endl;
break;
}
cout<<"no record found"<<endl;
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在创建一个循环,并明确告诉它在第一次迭代后
break
退出循环。尝试这样写:You are making a loop and explicitly telling it to
break
out of it after the first iteration. Try writting it like this:您需要一个函数来给出要搜索的元素,找到该元素的索引。不要自己写,在数组上使用
std::find
我认为在你的情况下最好至少使用
std::vector
或struct
现在将您的信息存储在两个数组中You need a function that given an element to search, find the index of that element. Don't write it by yourself, use
std::find
on arrayI think in your case it's better to use at least
std::vector
or astruct
to store your information now in the two arrays