user1428720
user1428720

Reputation: 1

Implementing counter when typing variable in array is typed

ive modified my code to include a counter and it seems to be working but i dont like how its implemented. it seems to count each letter and output the count before the word is finished.

#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');
}

i would like that the output for an input of game would be somethhing along the lines of

g*m*
2

all im getting now is

g*
1m*
2

also how could i modify the code so that uppercase letters are also read as lower case? is there something like isupper or islower in C?

Upvotes: 0

Views: 90

Answers (1)

Viktor Latypov
Viktor Latypov

Reputation: 14467

If you want the counter to be printed only once, then move it outside of the do-while loop.

#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;
}

Upvotes: 1

Related Questions