Search code examples
ceofgetchar

Verify that the expression getchar() != EOF is 0 or 1


Problem

Verify that the expression getchar() != EOF is 0 or 1.

Approach

I have tried to write a program which will first take an input other than EOF and thus will print the value 1. Next it will take EOF as input and will print 0.

/* Program to verify that the value of the expression getchar() != EOF is 0 or 1 */

#include <stdio.h>

int main()
{
    printf("Inputting something other than EOF, value of the expression is %d\n", getchar() != EOF);
    printf("Inputting EOF, value of the expression is %d\n", getchar() != EOF);
    printf("It is verified that the expression getchar() != EOF is 0 or 1.\n");
    return  0;
}`

Issue:

But the when I give an input it does not print the first line and waits for the next input. It directly prints all the lines. How can I make the second line take the next input?


Solution

  • The issue here is due to the working principle of getchar(). It will start reading only after ENTER key pressed, and in that case, the next getchar() (in the second printf()) will read the newline(\n) from the input buffer and won't wait for any user input.

    Solution: add one more getchar() call before the second printf(). This will eat the \n.