Reputation: 4990
I would like to return "jackpot" if there is only one character in "toParse" and the character is either "+" or "0". What is the most elegant way to do this? I tried this but apparently it does not work as it returns "jackpot" all the time for unknown reason.
char* ParseNRZI::parse(const char* toParse){
if (toParse=="+"||toParse=="0")
return "jackpot";
}
Upvotes: 1
Views: 1612
Reputation: 45420
use strcmp
if you compare C style pointers to char
char* ParseNRZI::parse(const char* toParse)
{
if (strcmp(toParse, "+") == 0 ||
strcmp(toParse, "0") == 0)
{
return "jackpot";
}
return "something else";
}
Or if you use std::string
you can use operator==
freely
std::string ParseNRZI::parse(const std::string& toParse)
{
if (toParse == "+" ||
toParse == "0")
{
return std::string("jackpot");
}
return std::string("something else");
}
For design point of view, you are wring a check function not a real parsing function. Then you can rewrite your function to:
bool isJackpot(const std::string& value)
{
if (toParse == "+" ||
toParse == "0")
{
return true;
}
return false;
}
and it can simplified to:
bool isJackpot(const std::string& value)
{
return value.find_first_of("0+") != std::string::npos;
}
Note: your function doesn't always return char*
in all branches it will invoke undefined behavior when toParse
is not +
or 0
. Make sure all your function branches return a value when function return type is not void
.
Upvotes: 4
Reputation: 1676
const char* ParseNRZI::parse(const char* toParse) const
{
if (( toParse != 0 ) &&
( toParse[0] == '+' || toParse[0] == '0' ) &&
( toParse[1] == 0 )
)
return "jackpot";
return "";
}
Upvotes: 0