我有一个结构,它拥有两个名称,但它们是字符形式 - 所以数组 char [2] [10] 它应该是两个名称,它们是最长十个字符。 我想通过它们进行搜索。如何搜索结构/文件中的名称
while (ans3==1)
{
cout << "\nPlease enter the name you want to search"
<<endl;
cin >> searchName;
for (int i=0; i < size; i++)
{
cout <<"\nsearching " <<endl;
for (int k=0; k< 10; k++)
if (MyData.name[i][k]==searchName[k])
{
cout << "\nName was found at position "<< k <<endl;
}
else
cout << "\nName not found at position " <<k <<endl;
}
cout << "\nDo you want to search for a name? (1 for y, 2 for n)" <<endl;
cin >> ans3;
}
这个编译,但没有做我想做的事。有人可以帮助吗?谢谢。
如果字符串少于9个字符,'for(int k = 0; k <10; k ++)'将在字符串结束后继续搜索。考虑使用['strncmp'](http://en.cppreference.com/w/c/string/byte/strncmp)。 – user4581301