if (array[n] == stringVariable) doesn't work!

I just want to use an if statement to compare between a string variable and an element inside an array, here is an example of what I'm trying to do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;
int main() {
int x;
string name;
string myArray[5] = {"Ab","Cd","Ef","Gh","Ij"};
cout << "Enter a name" << endl;
cin >> name;
while (x <= 5) {
if (myArray[x] == name) { cout << "Your element number is: " << x << endl; }
++x;
}
return 0;
}


in line 11 I get an error message from the compliler says: Invalid operands to binary expression ('int' and 'String' (aka 'basic_string<char>'))

Why? I am comparing two strings not a string with an int? What's wrong here?

I'm using Xcode!

** Also, how can I stop the while loop in line 11 if the if statement there was true? because I have a lot of elements and I don't want to check them all.

Thanks in advance!
Last edited on
You did not assign an initial value to variable x. Its initial value shall be equal to 0.

And inside the while loop the condition shall be x < 5.

To exit the loop use the break statement.
Sorry, actually I did assign x =0 in my actual code but I forgot to write it here, still same problem!

And thanks for the x < x notice and the exit loop help! :)
The code is correct except the errors I pointed out.
If this isn't your exact code, it's possible you created strings with more than one word, or another delimiter. Try outputting name and see if it matches what was typed in. If you are having issues typing multiple words, try using getline instead of cin to assign name.
as vlad pointed out set a default to x=0;

Remove the = to 5 in the loop since you only have 5 elements in the array.
0,1,2,3,4 the index cant =5 just <

I don't see that anything would be wrong other than "Cd" is not the same as "cd" in case your testing those to be alike
Last edited on
vlad from moscow: Thanks man, you were right! I found that I've declared my variable twice one as a string and once as a char! I didn't notice it because it was in the middle of the messy codes :\

Volatile Pulse:
Thanks for your contibution, and I just changed all my cins to getlines :)

bmiller:
Got your point, Thank you!
Topic archived. No new replies allowed.