0

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;
}
Stanislaw T
  • 420
  • 1
  • 6
  • 20
  • 1
    stdin never ends - it's kind of paused instead. Try it with a file. (You may want to google about stdin/stdout/stderr - which are special streams). – JeffRSon Nov 24 '13 at 20:38
  • How are you *ending* your input? and [`ferror()`](http://en.cppreference.com/w/c/io/ferror) is only going to report true when *the stream* is in an error state; not when you enter data that is invalid. *That* error is returned by [`scanf()`](http://en.cppreference.com/w/c/io/fscanf), which you're appropriately checking for. – WhozCraig Nov 24 '13 at 20:39
  • @JeffRSon: stdin from a tty ends, when you send EOF to the tty. On many terminals Ctrl+D will do that. – David Foerster Nov 24 '13 at 21:30

1 Answers1

0

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.

Stanislaw T
  • 420
  • 1
  • 6
  • 20