What is wrong with this C program to count the occurences of each vowel?

前端 未结 5 2099
無奈伤痛
無奈伤痛 2021-01-22 20:47

PROBLEM:

Write a C program that prompts the user to enter a string of characters terminated by ENTER key (i.e. ‘\\n’) and then count the total number of the occurrence o

5条回答
  •  暖寄归人
    2021-01-22 21:11

    First of all you should put the return type for main: int ( ex: int main() ), this did not break your code but it the C standard and rises a warning from the compiler.

    Chars in C take the numerical value from the ASCII encoding standard: http://upload.wikimedia.org/wikipedia/commons/1/1b/ASCII-Table-wide.svg, look at the values there ( 'a' is 97 for example), more on wikipedia : http://en.wikipedia.org/wiki/ASCII

    All you do in your last for loop is compare the character to a,b,c,d,e.

    What I would recommend you to do is make a switch for the character:

    switch(c) {
        case 'a':
        case 'A':
            counter[0]++;
            break;
        case 'e':
        case 'E':
            counter[1]++;
            break;
        case 'i':
        case 'I':
            counter[2]++;
            break;
        case 'o':
        case 'O':
            counter[3]++;
            break;
        case 'u':
        case 'U':
            counter[4]++;
            break;
    }
    

    Alternatively, you could make five if statements.

    It should work fine now.

提交回复
热议问题