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

前端 未结 5 2188
無奈伤痛
無奈伤痛 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:31

    I think this is what you are trying to do:

    printf("Please enter a string terminated by ENTER key:\n");
    while((c = getchar()) != '\n')
    {
        if (c=='a' || c=='A')
            counter[0]++;
        else if (c=='e' || c=='E')
            counter[1]++;
        else if (c=='i' || c=='I')
            counter[2]++;
        else if (c=='o' || c=='O')
            counter[3]++;
        else if (c=='u' || c=='U')
            counter[4]++;
    }
    for(i = 0; i < 5; i++)
        printf("counter[%d] = %d\n", i, counter[i]);
    

    OR using switch:

    printf("Please enter a string terminated by ENTER key:\n");
    while((c = getchar()) != '\n')
    {
        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;
            default: break;
        }
    }
    for(i = 0; i < 5; i++)
        printf("counter[%d] = %d\n", i, counter[i]);
    

提交回复
热议问题