3dWafle
3dWafle

Reputation: 1

Why does it give me an error no "operator=="?

This line is an error and I don't know why. The compiler is telling me that the string array can't be converted to a string variable. The search is a string variable the user types in to look for names. And the names[count] is checking through an array of names.

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;
        }
    }

Upvotes: 0

Views: 75

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595412

Your question title mentions operator==, but there is no use of operator== anywhere in the code you have shown.

Your search logic is all wrong, though. First off, it is in the wrong place, it should not be inside the 2nd for loop at all, it needs to be moved up 1 level. And second, it is using the assignment operator= when it should be using the comparison operator== instead. And third, it is handling its output incorrectly.

Try something more like this instead:

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;
}
*/

Upvotes: 0

Charlie Robles
Charlie Robles

Reputation: 39

Is giving you this error because you are using the = assignment operator instead of the == comparison operator. Only use the former when assigning values to variables and the second for comparing variables in a condition.

I hope this helps: https://www.geeksforgeeks.org/what-is-the-difference-between-assignment-and-equal-to-operators/

Have a good one and happy hacking!

Upvotes: 2

Related Questions