Простой вопрос.Оператор сравнения строк C++
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;
}
У меня есть массив с 5 цветами, но независимо от ввода я прихожу к функции else. Использую ли я правильный оператор сравнения для сравнения строк? Я знаю, что эквивалент java для этого - .equals(). Любая помощь будет оценена!
EDIT: Вот мой весь код, который более четко показывает проблему.
#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;
}
вы объявить ключ в виде строки? – CIsForCookies
Да, я объявил это как строку ранее в коде, я сейчас это изменил. – Shambaree
, если ваш массив является строковым массивом, который должен работать. вы можете показать объявление массива? – CIsForCookies