gpt4 book ai didi

C++ 关系运算符 == 与字符串

转载 作者:行者123 更新时间:2023-11-30 03:32:06 25 4
gpt4 key购买 nike

我收到一个错误,提示我无法使用关系运算符“==”来测试字符串与字符串的匹配。是否因为数组(字符串)而需要不同的运算符?

int searchArray(string name, string &firstNameArray); // declares the function

int main()
{
string firstNameArray[7] = { "Jim", "Tuyet", "Ann", "Roberto", "Crystal", "Valla", "Mathilda" }; //declares and intializes the array

string name = "";
cout << "What's your name?";
getline(cin, name);

searchArray(name, firstNameArray[7]); // using the function


return 0;
}

int searchArray(string name, string &firstNameArray) { //defining the function


int position = 0; //declaring and intializing the return variable - positions 0 thru 6 for array elements and position 7 for not in array

for (int i = 0; i < 7; i++) { //looping through the array

if (firstNameArray[i] == name) //**error code "no operator "==" matches these operands
{
position == firstNameArray[i];
}
else
{
position == 7;
}

}

return position;

}

最佳答案

更正/建议 - 有关评论的更多详细信息:

    //const references
//use of vector
//use of vector size variable

int searchArray(const string & name, const vector<string> & firstNameArray) {
int position = -1; //declaring and intializing the return variable - positions 0 thru 6 for array elements and position 7 for not in array

for (int i = 0; i < firstNameArray.size(); i++) { //looping through the array
//== is for comparison
if (firstNameArray[i] == name)
{
position = i; //= is for assignment
break; // without break always returns not found
}
}
return position;
}

int main(int argc,const char * argv[]) {

vector<string> firstNameArray = { "Jim", "Tuyet", "Ann", "Roberto", "Crystal", "Valla", "Mathilda" }; //declares and intializes the array

string name ;
cout << "What's your name?";

getline(cin, name);

cout << "position: " << searchArray(name, firstNameArray) << endl;


return 0;
}

关于C++ 关系运算符 == 与字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com