这是我的代码: 我在使用指针时遇到问题。所以*string显示当前地址的字符,string += 1增加指针的地址指向下一个字符,但是程序每次执行都返回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] = '\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;
}
最佳答案
在您的程序中,您错误地放置了一个“;”在 while 循环之后,这使得它成为带有空体的 while 循环 -
while (( c = getchar() ) != '\n');
因为这个“;” while 循环体中的代码不会按预期执行。 去除 ”;”并且您的程序将运行。
关于c - C语言中,如何用指针计算一个字符串中有多少个元音字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46592129/