C++ 错误:从“char”到“const char*”的无效转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15969281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Error: Invalid conversion from 'char' to 'const char*'
提问by LazySloth13
I'm completely new to C++ and I created this function:
我对 C++ 完全陌生,我创建了这个函数:
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?
但它返回到以下error: invalid conversion from 'char' to 'const char*' [-fpermissive]
. 谁能帮我理解这意味着什么?
采纳答案by ForEveR
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
compWord[x]
获取char
而您试图将其分配给string
,这是错误的。但是,您的代码应该类似于
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;
}
回答by Manoj Awasthi
string compLetter = compWord[x];
string compLetter = compWord[x];
should be
应该
char compLetter = compWord[x];
char compLetter = compWord[x];
回答by SlxS
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.
应该做的伎俩。
回答by Saanti
compWord[x] gives you the x'th character in string compWord, which you are then trying to assign to a string.
compWord[x] 为您提供字符串 compWord 中的第 x 个字符,然后您尝试将其分配给字符串。
You should either compare both strings directly, or iterate over them in parallel and compare character by character.
您应该直接比较两个字符串,或者并行迭代它们并逐个字符地比较。
回答by Peter Wood
You can use std::string::find
to see whether a character is in the string
. If it's not, it returns std::string::npos
:
您可以使用std::string::find
来查看字符是否在string
. 如果不是,则返回std::string::npos
:
bool guessLetter(string compWord)
{
cout << "Guess a letter: ";
char userLetter;
cin >> userLetter;
return compWord.find(userLetter) != string::npos;
}
}