cwhile-loopchargetchar

While loop in C prints the same line more than once


char ch;
int nr=0;

printf("\n: "); 
ch = getchar();

while(ch != 'q' && ch != 'Q'){
    ch = tolower(ch);
    if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u')
        nr++;
    
    printf("something");
    ch = getchar();
}
    
printf("vocale: %d", nr);

its supposed to count the number of vowels until the user presses q or Q. it's such a silly program and yet i cant get past it.


Solution

  • The problem is, that the input only gets flushed to your program whenever the user presses enter. Another reason why it seems not to work is, because you don't have a newline at the end of you output (printf("vocale: %d", nr); ), which causes the output not to be flushed to the terminal when the program ends. Fix this and your program works, but maybe not as you expect it to, because you still have to press enter. It will still only count to the first 'q' found.

    int main() {
        char ch;
        int nr = 0;
        printf(": "); 
        while(tolower(ch = getchar()) != 'q'){
            ch = tolower(ch);
            if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u')
                nr++;
        }
        printf("vocale: %d\n", nr);
    }
    

    The program:

    : aeu q oi (here I pressed enter)
    vocale: 3