String Comparator Operator C++

189 views Asked by At

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;

}

2

There are 2 answers

0
norisknofun On

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.

1
R Sahu On

The logic you are using in the following block is not right even when you change the compare line.

for (int i = 0; i < 5; i++)
{
    if (ARRAY[i] == key)
        cout <<"Found " << key <<endl;
    else
        cout << key <<" not found" <<endl;
}

Let's say key == "Purple". You won't see the match until the last item. In the mean time, you will be printing the not found string for all the other colors. Change the logic to:

bool found = false;
for (int i = 0; i < 5; i++)
{
   if (ARRAY[i] == key)
   {
      found = true;
      break
   }
}

if ( found )
   cout <<"Found " << key <<endl;
else
   cout << key <<" not found" <<endl;

You can make the code compact by using std::find (Thanks @LightnessRacesinOrbit):

if (std::find(std::begin(ARRAY), std::end(ARRAY), key) != std::end(ARRAY))
   cout << "Found " << key << endl;
else
   cout << key << " not found" << endl;