lundi 15 janvier 2018

clever way to reduce if-elseif statements

I've developing a code to restrict SpinBox to letters instead of integers. Everything is working fine but I would like to reduce the if-elseif statements if there is any clever way. This is the code

std::string AlphaSpinBox::textFromValue(int value) 
{
    // I feel the code is Ok but willing to change it if there is a better way.
    // value is restricted [0-25] inclusive. 
    std::string str("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    return std::string(str[value]);
}

int AlphaSpinBox::valueFromText(std::string &text) 
{
    // can I shorten the following?!
    // text is solely one letter (i.e. either upper or lower)
    if(text == 'A' || text == 'a')
        return 0;
    else if(text == 'B' || text == 'b' )
        return 1;
    else if(text == 'C' || text == 'c')
        return 2;
    else if(text == 'D' || text == 'd')
        return 3;
    ... to z letter
}

Aucun commentaire:

Enregistrer un commentaire