Home > Enterprise >  While loop in C prints the same line more than once
While loop in C prints the same line more than once

Time:11-02

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.

CodePudding user response:

Instead of using getchar

ch = getchar();

that also reads white space characters use scanf like

scanf( " %c", &ch );

Pay attention to the leading space in the format string. It allows to skip white space characters.

For example

while ( scanf( " %c", &ch ) == 1 && ch != 'q' && ch != 'Q'){

Also it will be more safer to write

ch = tolower( ( unsigned char )ch );

CodePudding user response:

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
  • Related