我试图对字符串执行索引搜索,但它运行但问题是它只打印出i [0]这是我的第一个条目。如果我查找另一个条目它不起作用。请帮忙.. 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;
}
}
答案 0 :(得分:1)
你正在做一个循环并在第一次迭代后明确告诉它break
。试着这样写:
bool found = false;
for(int i=0;i<size;i++){
if(fn[i] == search){ // No need to check for(i < size)
found = true;
cout<<"Result found "<<fn[i]<<" "<<ln[i]<<endl;
break;
}
}
if(!found)
cout<<"no record found"<<endl;
答案 1 :(得分:0)
您需要一个给定要搜索的元素的函数,找到该元素的索引。不要自己编写,在数组上使用std::find
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string xx[3];
xx[0] = "zero";
xx[1] = "one";
xx[2] = "two";
int index = std::find(xx, xx+3, "two") - xx;
if (index < 3) std::cout << "found in position: " << index << endl;
else std::cout << "not found" << endl;
}
我认为在您的情况下,最好至少使用std::vector
或struct
将您的信息存储在两个数组中