0

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.

1
  • Assuming that, as its name suggests, letter is always a single letter then if (entry[i] == letter[0]) will work. Basic fact about C++ is that strings and characters are different types. Commented Jan 25, 2023 at 22:04

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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 the 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.