键入在数组中键入变量时实现计数器

时间:2012-05-31 15:46:38

标签: c arrays counter

我修改了我的代码以包含一个计数器,它似乎工作但我不喜欢它的实现方式。它似乎计算每个字母并在单词结束前输出计数。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char** argv)
{
char C;
char vowels[]={'a','e','i','o','u'};
int counter=0;
    do
    {
    C = getchar();
    if(memchr(vowels,C, sizeof(vowels)))
        {printf("*\n");
        counter++;
        printf("%i", counter);
        }
    else
        {
        printf("%c",C);
        }



    }while (C!='Q');
}

我希望游戏输入的输出可以是

g*m*
2

我现在所有人都是

g*
1m*
2

我怎么能修改代码,以便大写字母也被视为小写? 在C中有类似isupper或islower的东西吗?

1 个答案:

答案 0 :(得分:1)

如果您希望计数器只打印一次,请将其移到do-while循环之外。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char** argv)
{
    char C;
    char vowels[]={'a','e','i','o','u'};
    int counter=0;
    while(1) {
        C = getchar();
        if(C == 'Q') { break; }
        C = tolower(C);
        if(memchr(vowels,C, sizeof(vowels))) {
            printf("*");
            counter++;
        }
        else
        {
            if(C == '\n') {
               printf("\n%i\n", counter);
               // reset the vowel counter here (dunno what the actual task is)
               counter = 0;
            } else {
               printf("%c",C);
            }
        }
    }

    return 0;
}