1
這是我的代碼: 我遇到了使用指針的問題。所以* string在當前地址處顯示字符,並且字符串+ = 1將指針的地址增加爲指向下一個字符,但程序每次都會返回一個零。最初,我有另一個整數變量添加到地址,int索引,但有人告訴我刪除它。在C中,如何使用指針來計算字符串中有多少元音?
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;
}
修復了程序。謝謝! – Gideon
@Gideon歡迎來到SO,如果這個答案爲你提供了一個解決你的問題的方法,請接受它,這會給你一些聲望,並告訴未來的讀者這個解決方案爲你工作。 –