Tuesday, August 16, 2011

Exercise 1-6

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

I can run the following program and feed it input like this:
# ./a.out < prog.c

#include <stdio.h>

int main(void)
{
  int c;
  int zero = 0, one = 0, other = 0;

  do
  {
    switch ((c=getchar())!=EOF)
    {
      case 0:
        zero=1;
        break;

      case 1:
        one=1;
        break;

      default:
        other=1;
        break;
    }
  }
  while (c != EOF);

  if (zero)
    printf ("The expression evaluated to 0 at least once.\n");

  if (one)
    printf ("The expression evaluated to 1 at least once.\n");

  if (other)
    printf ("The expression evaluated to an unexpected result at least once.\n");

  return 0;
}

No comments:

Post a Comment