Search code examples
cstdinfeof

basic stream handling in c


I am just baffled by basic stream handling in C. Even after an hour of googling and reading on the issue I am none the wiser ( and it is not my first attempt to delve into this). I am trying to read numbers from input until EOF or non-number is reached and be able to distinguish between those 2. From what I understand this should work, but the feof and ferror conditions are never true. Why is that ? And could somebody provide me with a working code snippet along with a dummy friendly in-depth explanation?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int number;
  printf("number or EOF:\n");

  while(scanf("%d",&number) == 1)
  {
          printf("read number %d\n",number);
  }
  if(ferror(stdin))printf("error reading\n");
  else if (feof(stdin))printf("eof reached\n");
  return 0;
}

Solution

  • My problem understanding the stream behaviour i was getting stemmed from one little peculiarity. I didnt know that in Windows console there is a newb unfriendly ambiguity , Ctrl+Z can be as read ASCII 0x1A if you enter input like 12 23 ^Z/enter/ but gets read as proper EOF, when you do 12 23 /enter/^Z/enter/. this code solves the issue

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
    
     printf("int or eof\n");
        int num;
        while( scanf("%d",&num) ==1 )
        {
            printf("the read number is  %d \n",num);
        }
        if(!feof(stdin) && getchar()!=0x1A)//first check if its read as EOF,
              //if it fails, call getchar for help to check for ^Z
        {
            printf("non-int error\n");
        }
        else printf("eof ok\n");
        system("PAUSE");
        return 0;
    

    I am sorry for the misleading question.