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>
usingnamespace 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.
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.
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 :)