Converting Letters to Numbers in C

前端 未结 10 1212
悲&欢浪女
悲&欢浪女 2020-11-30 07:22

I\'m trying to write a code that would convert letters into numbers. For example A ==> 0 B ==> 1 C ==> 2 and so on. Im thinking of writing 26 if statements. I\'m wondering

10条回答
  •  一生所求
    2020-11-30 07:33

    Another, far worse (but still better than 26 if statements) alternative is to use switch/case:

    switch(letter)
    {
    case 'A':
    case 'a': // don't use this line if you want only capital letters
        num = 0;
        break;
    case 'B':
    case 'b': // same as above about 'a'
        num = 1;
        break;
    /* and so on and so on */
    default:
        fprintf(stderr, "WTF?\n");
    }
    

    Consider this only if there is absolutely no relationship between the letter and its code. Since there is a clear sequential relationship between the letter and the code in your case, using this is rather silly and going to be awful to maintain, but if you had to encode random characters to random values, this would be the way to avoid writing a zillion if()/else if()/else if()/else statements.

提交回复
热议问题