我试图将字符串与结构向量中的struct元素进行比较。我已正确创建了向量,但似乎无法使if语句生效。它总是返回true。这样做的正确方法是什么? 的结构:
struct customer{
string name;
string phoneNumber;
string addressLine1;
string addressLine2;
};
循环迭代包含if语句的向量:
cout<<"Input customer's phone number: ", cin>>phoneNumber, cout<<endl;
int foundIndex = 0;
bool found = false;
for(int it = 1; it < customers.size(); it++){
if(phoneNumber.compare(customers[it].phoneNumber)){
cout<<"Found at "<<foundIndex<<endl;
cout<<"Name: "<<customers[foundIndex].name<<endl;
cout<<"Phone Number: "<<customers[foundIndex].phoneNumber<<endl;
cout<<"Address: "<<customers[foundIndex].addressLine1<<endl<<" "<<customers[foundIndex].addressLine2<<endl;
found = true;
break;
}
}
从CSV填充Vector的功能:
vector<customer> readFile(void){
string name;
string phoneNumber;
string addressLine1;
string addressLine2;
vector<customer> customers;
vector<string> temper;
customer temp;
fstream ioFile;
ioFile.open("customers.csv", fstream::in | fstream::out | fstream::app);
while (!ioFile.eof()){
getline(ioFile, name);
temper = split(name);
temp.name = temper[0];
temp.phoneNumber = temper[1];
temp.addressLine1 = temper[2];
temp.addressLine2 = temper[3];
customers.push_back(temp);
}
ioFile.close();
return customers;
}
答案 0 :(得分:2)
标准库提供std::find_if
功能,使用自定义谓词搜索容器。
std::vector<customer> customers;
auto result = std::find_if(
customers.begin(),
customers.end(),
[&phoneNumber](customer const& c) {
return c.phoneNumber == phoneNumber;
}
);
if (result != customers.end()) {
std::cout << *result << '\n';
}
答案 1 :(得分:2)
通常,您编写的代码应该有效,但您有一些问题需要监督
您正在初始化foundIndex = 0但findIndex永远不会更改(为此 代码片段没有必要。 我修改了你的代码。它现在应该工作
cout<<"Input customer's phone number: ", cin>>phoneNumber, cout<<endl;
bool found = false;
for(int it = 0; it < customers.size(); it++){
if(phoneNumber.compare(customers[it].phoneNumber){
cout<<"Found at "<<it<<endl;
cout<<"Name: "<<customers[it].name<<endl;
cout<<"Phone Number: "<<customers[it].phoneNumber<<endl;
cout<<"Address: "<<customers[it].addressLine1<<endl<<" "<<customers[it].addressLine2<<endl;
found = true;
break;
}
}
你是否认识到我使用“它”? 如果你需要foundIndex 添加
foundIndex=it;
之前
break;
在不改变FoundIndex的情况下,您将始终获得第一个条目。
答案 2 :(得分:1)
替换
phoneNumber.compare(客户[它] .phoneNumber)
通过
phoneNumber.compare(customers [it] .phoneNumber)== 0
说明:compare是一个度量,如果不存在差异则返回零。 因此,例如,&#34; Foo&#34; .compare(&#34; Bar&#34;)&gt; 0,因此评估为真,而&#34; Foo&#34; .compare(&#34; Foo&#34;)= 0如果用作布尔值,将评估为false。
中的示例答案 3 :(得分:1)
std::string::compare
会返回0
。 phoneNumber.compare(customers[it].phoneNumber)
对于匹配数字将为false,对于错误的数字为true。只需使用==
运算符:
for (size_t i = 0; i < customers.size(); ++i)
{
if (customers[i].phoneNumber == phoneNumber)
{
std::cout << "Found: " << customers[i].name;
break;
}
}
要改进代码,您可以使用标准库中的std::find_if
模板:
auto it = std::find_if(begin(customers), end(customers),
[&phoneNumber](const customer& c) {
return c.phoneNumber == phoneNumber;
});
if (it != end(customers))
std::cout << it->name;