LazySloth13
LazySloth13

Reputation: 2487

C++ Error: Invalid conversion from 'char' to 'const char*'

I'm completely new to C++ and I created this function:

bool guessWord(string compWord)
{
    cout << "Guess a letter: ";
    string userLetter;
    cin >> userLetter;
    for (unsigned int x = 0; x < compWord.length(); x++)
    {
        string compLetter = compWord[x];
        if (compLetter == userLetter)
        {
            return true;
        }
    }
    return false;
}

But it returns to following error: invalid conversion from 'char' to 'const char*' [-fpermissive]. Can anyone help me understand what this means?

Upvotes: 8

Views: 59076

Answers (5)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You can use std::string::find to see whether a character is in the string. If it's not, it returns std::string::npos:

bool guessLetter(string compWord)
{
    cout << "Guess a letter: ";
    char userLetter;
    cin >> userLetter;
    return compWord.find(userLetter) != string::npos;

}

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

string compLetter = compWord[x];

compWord[x] gets char and you are trying to assign it to string, that's wrong. However, your code should be something like

bool guessWord(string compWord)
{
    cout << "Guess a letter: ";
    char userLetter;
    cin >> userLetter;
    for (unsigned int x = 0; x < compWord.length(); x++)
    {
        char compLetter = compWord[x];
        if (compLetter == userLetter)
        {
            return true;
        }
    }
    return false;
}

Upvotes: 4

Saanti
Saanti

Reputation: 11

compWord[x] gives you the x'th character in string compWord, which you are then trying to assign to a string.

You should either compare both strings directly, or iterate over them in parallel and compare character by character.

Upvotes: 0

SlxS
SlxS

Reputation: 413

On this line

string compLetter = compWord[x];

You're assigning a char to a string. Changing it to

char compLetter = compWord[x];

Should do the trick.

Upvotes: 1

Manoj Awasthi
Manoj Awasthi

Reputation: 3520

string compLetter = compWord[x];

should be

char compLetter = compWord[x];

Upvotes: 1

Related Questions