C ++ error: invalid conversion from 'char' to 'const char *'

I am 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 he returns to the next error: invalid conversion from 'char' to 'const char*' [-fpermissive]. Can someone help me understand what this means?

+5
source share
5 answers
string compLetter = compWord[x];

compWord[x]gets char, and you try to appropriate it string, which is 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;
}
+4
source

string compLetter = compWord[x];

it should be

char compLetter = compWord[x];

+1
source

string compLetter = compWord[x];

char .

char compLetter = compWord[x];

.

+1

compWord [x] x'th string compWord, .

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

0
source

You can use std::string::findto see if the character is in string. If it is not, it returns std::string::npos:

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

}

0
source

All Articles