如果“toParse”中只有一个字符并且该字符是“+”或“0”,我想返回“jackpot”。最优雅的方法是什么?我试过这个,但显然它不起作用,因为它一直返回“累积奖金”,原因不明。
char* ParseNRZI::parse(const char* toParse){
if (toParse=="+"||toParse=="0")
return "jackpot";
}
如果“toParse”中只有一个字符并且该字符是“+”或“0”,我想返回“jackpot”。最优雅的方法是什么?我试过这个,但显然它不起作用,因为它一直返回“累积奖金”,原因不明。
char* ParseNRZI::parse(const char* toParse){
if (toParse=="+"||toParse=="0")
return "jackpot";
}
strcmp
如果将 C 样式指针与 char 进行比较,则使用
char* ParseNRZI::parse(const char* toParse)
{
if (strcmp(toParse, "+") == 0 ||
strcmp(toParse, "0") == 0)
{
return "jackpot";
}
return "something else";
}
或者如果你使用std::string
你可以operator==
自由使用
std::string ParseNRZI::parse(const std::string& toParse)
{
if (toParse == "+" ||
toParse == "0")
{
return std::string("jackpot");
}
return std::string("something else");
}
从设计的角度来看,您正在编写检查功能而不是真正的解析功能。然后你可以将你的函数重写为:
bool isJackpot(const std::string& value)
{
if (toParse == "+" ||
toParse == "0")
{
return true;
}
return false;
}
它可以简化为:
bool isJackpot(const std::string& value)
{
return value.find_first_of("0+") != std::string::npos;
}
注意:您的函数并不总是在所有分支中返回,它会在is not或char*
时调用未定义的行为。当函数返回类型不是 时,确保所有函数分支都返回一个值。toParse
+
0
void
const char* ParseNRZI::parse(const char* toParse) const
{
if (( toParse != 0 ) &&
( toParse[0] == '+' || toParse[0] == '0' ) &&
( toParse[1] == 0 )
)
return "jackpot";
return "";
}