在C中,如何使用指针来计算字符串中的元音数量?

时间:2017-10-05 18:04:36

标签: c pointers counting

这是我的代码: 我在使用指针时遇到问题。因此* string显示当前地址处的字符,而string + = 1会将指针的地址增加为指向下一个字符,但程序每次执行时都返回零。最初,我有另一个整数变量添加到地址,int索引,但有人告诉我删除它。

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] = '\0';
 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 != '\0')
 {
      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;
}

1 个答案:

答案 0 :(得分:0)

在你的程序中,你错误地提出了一个&#34 ;;"在while循环之后,它将循环与空体 -

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

因为这个";" while循环体中的代码不会按预期执行。 删除";"并且您的计划将有效。