簡體   English   中英

為什么它給我一個錯誤 no “operator==”?

[英]Why does it give me an error no “operator==”?

這條線是一個錯誤,我不知道為什么。 編譯器告訴我字符串數組不能轉換為字符串變量。 搜索是用戶鍵入以查找名稱的字符串變量。 names[count] 正在檢查一個名稱數組。

string search;
string names[5]={};
for(int count=0; count<5; count++)
{
    cout<<"Enter a name"<<endl;
    cin>>names[count];
}
cout<<"Names entered"<<endl;
for(int count=0; count<5; count++)
{
    cout<<names[count]<<endl;
    cout<<"What name would you like to search for"<<endl;
    cin>>search;
    for(int count=0; count<5; count++)
    {
        if(names[count]=search)
        {
            cout<<search<<"is on array "<<count<<endl;
        }
        else
        {
            cout<<search<<"is not on the list"<<endl;
        }
    }

給你這個錯誤是因為你使用的是=賦值運算符而不是==比較運算符。 僅在為變量賦值時使用前者,在比較條件中的變量時使用第二個。

我希望這會有所幫助: https://www.geeksforgeeks.org/what-is-the-difference-between-assignment-and-equal-to-operators/

有一個好的和快樂的黑客!

您的問題標題提到了operator== ,但在您顯示的代碼中的任何地方都沒有使用operator==

但是,您的搜索邏輯全錯了。 首先,它在錯誤的位置,它根本不應該在第二個for循環內,它需要向上移動 1 級。 其次,它在應該使用比較運算符operator==時使用賦值operator= 第三,它錯誤地處理了它的 output。

嘗試更多類似的東西:

string search;
string names[5];

for(int count = 0; count < 5; ++count)
{
    cout << "Enter a name" << endl;
    cin >> names[count];
}

cout << "Names entered" << endl;
for(int count = 0; count < 5; ++count)
{
    cout << names[count] << endl;
}

cout << "What name would you like to search for" << endl;
cin >> search;

int found = -1;
for(int count = 0; count < 5; ++count)
{
    if (names[count] == search)
    {
        found = count;
        break;
    }
}

if (found != -1)
{
    cout << search << " is on array " << found << endl;
}
else
{
    cout << search << " is not on the list" << endl;
}


/* alternatively:

#include <algorithm>
#include <iterator>

string *namesEnd = &names[5];
if (std::find(names, namesEnd, search) != namesEnd)
{
    cout << search << " is on array " << std::distance(names, found) << endl;
}
else
{
    cout << search << " is not on the list" << endl;
}
*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM