Simple question.
cout << "What color do you want to search for?" << endl;
string key;
string ARRAY[5];
cin >> key;
for (int i = 0; i < 5; i ++)
{
if (ARRAY[i] == key)
cout << "Found " << key << endl;
else
cout << key << " not found" << endl;
}
I have an array with 5 colors, but no matter the input I arrive at the else function. Am I using the correct comparison operator to compare strings? I know the java equivalent for this is .equals(). Any help would be appreciated!
EDIT: Here is my whole code that more clearly shows the problem.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
string ARRAY[5];
int main()
{
ofstream myFile; //creates a file writer object
myFile.open("searchfile.txt"); //creates a file named "searchfile.txt"
myFile << "Orange" <<endl << "Green" <<endl << "Blue" <<endl << "Red" <<endl << "Purple" <<endl;
myFile.close();
string key;
string LIST;
ifstream myFile2; //creates a file reader object
myFile2.open("searchfile.txt");
while (!myFile2.eof()) //if not at the end of the file, continue reading
{
for (int i = 0; i < 5; i++)
{
getline(myFile2, LIST); //stores the value in string variable 'LIST'
ARRAY[i] = LIST;
cout << ARRAY[i] <<endl;
}//end for
}//end while
myFile2.close();
cout <<"What do you want to search for?" <<endl;
cin >> key;
key = "Red";
for (int i = 0; i < 5; i++)
{
if (ARRAY[i].equal(key))
cout <<"Found " << key <<endl;
else
cout << key <<" not found" <<endl;
//end if
}
return 0;
}
The code is semantically correct for what you want to do. Beware of
cin >> key
: if what you type contains a space,key
will contain only the first word entered.