Home > front end >  Why the characters in buffer cannot enter a while loop?
Why the characters in buffer cannot enter a while loop?

Time:05-15

why there is no "*" in output? the input is : abcde[enter key]

#include<stdio.h>
int main(void){
    char ch;
    while ((ch=getchar( ))== 'e')
        printf(" * ");
    
    return 0;
}

I was wondering that the abcd'\n' will be stored in buffer when i click the enter key, and the getchar() will constantly read it until catch the char 'e' and print the "*"

CodePudding user response:

With input "abcde", there is no "*" printed because while loop reads character by character from standard input, while the read character is equal to character 'e'. Once you enter a character different from 'e' while loop breaks. As your input is "abcde" in first iteration of while loop variable ch becomes equal to 'a' and condition ch == 'e' is equal to false and after that loop breaks. That while loop is same like this loop:

while (1){
    ch = getchar();
    if (ch != 'e') break;
    printf(" * ");
}

CodePudding user response:

When you enter "abcd" what's the first value returned by getchar() and what happens to your loop?

  • Related