Making a switch statement in C with an array?

末鹿安然 提交于 2019-12-24 00:36:03

问题


I am trying to make a switch statement that takes in a word into an array and then throws each letter through a switch statement and allocates a point to each letter depending on which letter it is and giving a final point value for the word, and I can't seem to get the array part right. Any help would be appreciated!

int main(){
int letter_points = 0;
char word[7];
int word_length = 7;
int i;
printf("Enter a Word\n");
scanf("%s", word);
for(i = 0; i < word_length; i++){

switch(word){
    //1 point
    case 'A':
    case 'E':
    case 'I':
    case 'L':
    case 'N':
    case 'O':
    case 'R':
    case 'S':
    case 'T':
    case 'U':
        letter_points++;
        break;
    //2 points
    case 'D':
    case 'G':
        letter_points += 2;
        break;
    //3 points
    case 'B':
    case 'C':
    case 'M':
    case 'P':
        letter_points += 3;
        break;
    //4 points
    case 'F':
    case 'H':
    case 'V':
    case 'W':
    case 'Y':
        letter_points += 4;
        break;
    //5 points
    case 'K':
        letter_points += 5;
        break;
    //8 points
    case 'J':
    case 'X':
        letter_points += 8;
        break;
    //10 points
    case 'Q':
    case 'Z':
        letter_points += 10;
        break;
}
}
printf("%d\n", letter_points);
return;
}

回答1:


Try using this

 switch(word[i]){ 

in the switch statement. As it stands, you are not testing each element in your array even though you are iterating over the range of the array. Having said that I would go for the approach suggested by Kerrek SB in the other answer. This is much neater and more compact.




回答2:


It would probably be faster to have a lookup array:

int const letter_score[26] = { 1, 2, 1, 3, ..., 10 };
/*                      key:   A  B  C  D        Z    */

score += letter_score[c - 'A'];   // or "toupper(word[i]) - 'A'"

Caveat: this requires an encoding in which the upper-case letters are arranged contiguously, such as Unicode or ASCII.




回答3:


The variable word is an array, but you want to switch on each character. Thus, you need:

switch(word[i])



回答4:


In C, you cannot use arrays in switch (and expressions for case). Also, the type passed to switch() and types specified in each case must match. So the most you can do is switch on a character. You almost got it right though, except that you are passing the whole array into switch. Use index to reference a character instead. For example:

switch (word[i]) {
 ...
}



回答5:


You have word as an array of size7, you cannot switch on the array, you have to swicth on each character of the array so use: switch(word[i])



来源:https://stackoverflow.com/questions/12427641/making-a-switch-statement-in-c-with-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!