FAST I/O discussion

I had a ques related to the recent discussion we had on fast I/O…using that function how do we read EOF!!!

I had to start a new Thread as the earlier one was closed…pls dont mind…:slight_smile:

1 Like

Modifying above answer :

  • EOF is macro defination included in header which is used as the value to represent an invalid character, which is handled by the 1st loop of your Fast i/o function.
  • The 2nd while loop of the function reads the characters whose ascii values are between 48-57, i.e(0-9) and if a character out of this range comes then simply the function breaks out of loop and returns the number.
  • scanf() function returns a value which represents number of input you have take. For eg: if(scanf("%d%d",&x,&y)==2) print(x); means to say if the number of input equals 2 then print 2.
  • Hence, if you dont have any input scanf() returns -1. So, EOF is used which expands to negative integral constant i.e -1. For eg: if(scanf("%d",&x)!=EOF) means in your input file a EOF will be written at the end, which is same as you don’t have any left input i.e if(scanf("%d",&x)!=-1).
  • So overall you should modify the function to return a value of -1 or EOF if no charcters in range of integer 0-9 found.
  • Code :

//#include< stdio.h >

int readint()
{
       int cc;
       while(  (cc = getchar())  &&  (cc < '0' || cc > '9')  )
       {
          if(cc==EOF) return EOF;
       }
       
       int ret = 0;
       while(cc >= '0' && cc <= '9')
       {
          ret = ret * 10 + cc - '0';
          cc = getchar();
       }
      return ret;
}
 
int main()
{
    int x;
    while( (x = readint())!=EOF )
    { 
        printf("%d\n",x) ;
    }
}
5 Likes

how can i be sure that there are no more inputs???
should i add a counter of some sort to see if it exceeds a particular value MAX(say arnd 1000 iterations) break out the loop make a flag saying that no more ips and then return -1…and then in main check if the EOF flag is true or no???

In the i/o function initialize ret to some value out of range of inputs given in problem. For eg: set ret = INT_MAX. In main func check if(ret==INT_MAX) then break out of loop. Also you may use flags. For eg: In your problem 0<n<10000000 then set ret to 0 initially and if 0<=n<10000000 then set ret to -1 initially.

1 Like

is this what i can use…http://ideone.com/dQyZBL

Yeah sure :slight_smile:

1 Like

ok…thanks a lot…:slight_smile:

1 Like