-1
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.

9
  • Please include a minimal reproducible example in your question. Commented Nov 1, 2022 at 19:55
  • Aside: what crime did y commit? Commented Nov 1, 2022 at 19:57
  • Of course it prints "something" every time. You've told it to. Commented Nov 1, 2022 at 19:58
  • It likely prints them all at once because your IO is buffered and you haven't printed a newline. Commented Nov 1, 2022 at 19:59
  • 1
    @500-InternalServerError 'y' is not a proper vowel in the English language. (though I've seen others mistakenly include it -- must be like that "New Math" stuff) Commented Nov 1, 2022 at 20:22

2 Answers 2

1

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 );
Sign up to request clarification or add additional context in comments.

Comments

-1

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

1 Comment

Just a note, the printf("vocale: %d", nr); after the close of the loop lacking a '\n' has nothing to do with streams not getting flushed (at that location). Streams are flushed and closed at program exit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.