Home > Back-end >  Invalid operands to binary expression [xcode c ]
Invalid operands to binary expression [xcode c ]

Time:01-26

Why do I have this error in my code?

void check_letter(string letter, string entry) {
    for(int i = 0; i < entry.length(); i  ) {
        if(entry[i] == letter) {

        }
    }
}

Invalid operands to binary expression ('std::basic_string<char>::value_type' (aka 'char') and 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char>>'))`

I want to check each letter in the word, so I check all letters of the word in a loop. I tried it on a array char (I made the array with individual letters from the word) and I had the same error.

CodePudding user response:

entry[i] is a char, letter is a std::string - and there is no bool operator==(const char&, const std::string&) so you can't compare the two for equality.

You could change the function to void check_letter(char letter, const string& entry) to make it search for an individual char in entry.

Note: std::string::find can search for an individual char (overload 4) and returns the index of the found char (or std::string::npos if not found).

CodePudding user response:

You are trying to compare a single character with a whole string

if(entry[i] == letter) 

Instead you could write for example

if ( letter.find( entry[i] ) != std::string::npos ) {
   //...

I tried it on a array char (I made the array with individual letters from the word) and I had the same error

You may not also to compare a whole array with a character. If for example the variable letter is declared as a character array then you could use standard C string function strchr declared in header <cstring> to determine whether a character is present in the array.

For example

#include <cstring>

//...

if ( strchr( letter, entry[i] ) != nullptr ) {
    //...
  

Also it is not a good idea to declare the function like

void check_letter(string letter, string entry);

You should declare parameters as having referenced types as for example

void check_letter(string &letter, string *entry);

Or you could add qualifier const if strings are not changed in teh function like

void check_letter( const string &letter, const string *entry);

Maybe it would be even better to use std::string_view instead of std::string as the function parameter type.

  • Related