C语言中,如何用指针计算一个字符串中有多少个元音字母?

In C, how to use pointers to count how many vowels in a string?

这是我的代码: 我在使用指针时遇到问题。所以*string显示的是当前地址的字符,string += 1增加指针的地址指向下一个字符,但是程序returns每次执行都是0。本来,我有另一个整数变量添加到地址,int index,但有人告诉我删除它。

void menu();
int vowels(char *);
int consonants(char *);
void CtoUpper(char *);
void CtoLower(char *);
void displayString(char *);

int main()
{
 menu();
}

void menu()
{
 char *string, string_holder[100], choice, input, c = ' ';

 int index = 0;

 printf("Please enter a string:");
 while (( c = getchar() ) != '\n');
 {
      string_holder[index] = c;
      index++;
 }
 string_holder[index] = '[=10=]';
 choice = ' ';
 string = string_holder;

 while (choice != 'X')
 {
      printf("                     Menu\n");
      printf("-------------------------------------------------\n");
      printf("A) Count the number of vowels in the string\n");
      printf("B) Count the number of consonants in the string\n");
      printf("C) Convert the string to uppercase\n");
      printf("D) Convert the string to lowercase\n");
      printf("E) Display the current string\n");
      printf("X) Display the current string\n\n");

      scanf(" %c", &choice);

      if (choice == 'A')
      {
           printf("The number of vowels in the string is ");
           printf("%d\n\n", vowels(string) );
      }
      /*else if (choice == 'B')
      {
           printf("The number of consonants is in the string is ");
           printf("%d\n\n", consonants(string) );
      }
      else if (choice == 'C')
      {
           CtoUpper(string);
           printf("The string has been converted to uppercase\n\n");
      }
      else if (choice == 'D')
      {
           CtoLower(string);
           printf("The string has been converted to lowercase\n\n");
      }
      else if (choice == 'E')
      {
           printf("Here is the string:\n");
           displayString(string);
      }*/
 }
}

int vowels(char *string)
{
 int number_of_vowels = 0;

 while (*string != '[=10=]')
 {
      switch (*string)
      {
           case 'a':
           case 'A':
           case 'e':
           case 'E':
           case 'i':
           case 'I':
           case 'o':
           case 'O':
           case 'u':
           case 'U':
                number_of_vowels += 1;
                break;
      }
      string++;
 }
 return number_of_vowels;
}

在你的程序中,你错误地放置了一个“;”在 while 循环之后使其成为空体的 while 循环 -

while (( c = getchar() ) != '\n');

因为这个“;” while 循环体中的代码不会按预期执行。 去除那个 ”;”并且您的程序将运行。