I have read so many questions about getchar() and its behaviour, but still I don't understand this simple code..
while (scanf("%d", &z) != 1) { while (getchar() != '\n'); printf ("Try again: ");} This code is to validate for characters.. From what I infer from this code is that if I input
Stackoverflow Then the whole line is pushed to the buffer with the newline '\n' also.. Then the getchar() reads each character from the buffer and returns an integer, cleaning the buffer.. In this case the while loop should loop 12 times (number of characters in Stackoverflow) until it reaches the '\n' character.. but actually it just loops once and the output is
Try again: means its out of loop and asking for scanf again.. It goes against my understanding of looping.. Maybe I misunderstood looping.. One additional question,, if getchar() returns integers then how it could be compared to characters like '\n'?