简单的问题。
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()。任何帮助将不胜感激!
编辑:这是我的整个代码,更清楚地显示了问题。
#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;
}
答案 0 :(得分:1)
即使更改比较线,您在以下块中使用的逻辑也不正确。
for (int i = 0; i < 5; i++)
{
if (ARRAY[i] == key)
cout <<"Found " << key <<endl;
else
cout << key <<" not found" <<endl;
}
我们说key == "Purple"
。在最后一项之前你不会看到比赛。同时,您将为所有其他颜色打印not found
字符串。将逻辑更改为:
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;
您可以使用std::find
(感谢@LightnessRacesinOrbit)使代码紧凑:
if (std::find(std::begin(ARRAY), std::end(ARRAY), key) != std::end(ARRAY))
cout << "Found " << key << endl;
else
cout << key << " not found" << endl;
答案 1 :(得分:0)
代码在语义上对于您想要执行的操作是正确的。
请注意cin >> key
:如果您输入的内容包含空格,key
将仅包含输入的第一个字词。
答案 2 :(得分:-2)