为什么会给我一个错误,而不是“ operator ==“?

时间:2020-05-06 19:24:50

标签: c++

此行是错误,我不知道为什么。编译器告诉我不能将字符串数组转换为字符串变量。搜索是用户输入以查找名称的字符串变量。并且名称[count]正在通过名称数组进行检查。

string search;
string names[5]={};
for(int count=0; count<5; count++)
{
    cout<<"Enter a name"<<endl;
    cin>>names[count];
}
cout<<"Names entered"<<endl;
for(int count=0; count<5; count++)
{
    cout<<names[count]<<endl;
    cout<<"What name would you like to search for"<<endl;
    cin>>search;
    for(int count=0; count<5; count++)
    {
        if(names[count]=search)
        {
            cout<<search<<"is on array "<<count<<endl;
        }
        else
        {
            cout<<search<<"is not on the list"<<endl;
        }
    }

2 个答案:

答案 0 :(得分:2)

出现此错误是因为您使用的是=赋值运算符,而不是==比较运算符。仅在为变量分配值时使用前者,而在条件中比较变量时才使用前者。

我希望这会有所帮助: https://www.geeksforgeeks.org/what-is-the-difference-between-assignment-and-equal-to-operators/

拥有一个愉快的黑客环境!

答案 1 :(得分:0)

您的问题标题提到了operator==,但是在您显示的代码中的任何地方都没有使用operator==

但是,您的搜索逻辑是完全错误的。首先,它位于错误的位置,它根本不应该位于第二个for循环内,需要将其上移一级。其次,它应该使用赋值operator=来代替比较operator==。第三,它不正确地处理其输出。

尝试更多类似方法:

string search;
string names[5];

for(int count = 0; count < 5; ++count)
{
    cout << "Enter a name" << endl;
    cin >> names[count];
}

cout << "Names entered" << endl;
for(int count = 0; count < 5; ++count)
{
    cout << names[count] << endl;
}

cout << "What name would you like to search for" << endl;
cin >> search;

int found = -1;
for(int count = 0; count < 5; ++count)
{
    if (names[count] == search)
    {
        found = count;
        break;
    }
}

if (found != -1)
{
    cout << search << " is on array " << found << endl;
}
else
{
    cout << search << " is not on the list" << endl;
}


/* alternatively:

#include <algorithm>
#include <iterator>

string *namesEnd = &names[5];
if (std::find(names, namesEnd, search) != namesEnd)
{
    cout << search << " is on array " << std::distance(names, found) << endl;
}
else
{
    cout << search << " is not on the list" << endl;
}
*/