Bonjour friends,
I am trying to get to work a switch on a string in C++, with the help of a hash. It became personal between me and this code, so I don't wanna give up and use an enum, even though I finally have only like 8 strings to put in switch cases.
Combining what I saw on other topics, I wrote this very simple and not so reliable function, but that is enough for what I want to do, as it's not professional.
My function :
constexpr long hashstr (const string &str, int h=0)
{
return !str[h] ? 55 : ( hashstr(str, h+1) *33) + (unsigned char)str[h];
}
I then call it in this very simple main function (for now), but it won't compile, telling me that the case is wrong (not a constant). I don't understand this issue, as for me the string taken in arg is a constant, plus the function returns a constant expression.
My main :
int main (void) {
string teststr;
cout << "test string :::> ";
cin >> teststr;
int tt = hashstr(teststr);
cout << "res --> " << tt << endl;
switch ( hashstr(teststr) )
{
case hashstr("rosathefloridaturtle") :
cout << "ROSA OK" << endl;
break;
default:
cout << "ERROR" << endl;
break;
}
return EXIT_SUCCESS;
}
Hoping that some of you can tell me what I'm not doing right...
Thank you by advance and greeting from France,
Haughty hi from Rosa the turtle,
SB
Aucun commentaire:
Enregistrer un commentaire