如何只接受 C 语言中的字符输入



这个程序只计算你在程序中输入的单词中的元音。 但我希望这个程序只接受字符而不是数字。有办法吗?

#include <stdio.h>
#define MAX 50
int countVowel(char[]);
void main()
{
    char text[MAX];
    int cVowel, sum;
    printf("Enter text : ");
    scanf("%s", text);
    cVowel = countVowel(text);
    printf("Text : [%s] has %d vowels", text, cVowel);
}
int countVowel(char t[])
{
    int i = 0, count = 0;
    while (i < MAX && t[i] != '')
    {
        if (t[i] == 'A' || t[i] == 'a' || t[i] == 'E' || t[i] == 'e'
                || t[i] == 'I' || t[i] == 'i' || t[i] == 'O' || t[i] == 'o'
                || t[i] == 'u' || t[i] == 'U')
            count++;
        i++;
    }
    return (count);
}

我试过使用atoi,但它不起作用:/

您可以使用 strpbrk:

返回指向 str1 中任何 属于 str2 的字符,如果没有,则为空指针 比赛。

int main(void) /* void main is not a valid signature */
{
    char text[MAX];
    int cVowel, sum;
    while (1) {
        printf("Enter text : ");
        scanf("%s", text);
        if (strpbrk(text, "0123456789") == NULL) {
            break;
        }
    }
    ...
}

@Keine Lust的答案是正确的,如果你想忽略整个字符串,如果它包含数字字符。

如果您只想忽略它们,那么在迭代字符串时,请检查当前字符是否>= 48<= 57(根据 ASCII 字符表(。如果该条件为真,则只需continue;迭代即可。

最新更新