c - The scanf function is accepting values infinately -



int n; int a[maxsize]; int b[maxsize]; int c[maxsize]; int i; printf("enter number of  elements(disks)\n"); scanf("%d",&n); printf("enter elements in ascending  order\n"); for(i=0;i<n;i++) {        scanf("%d",&a[i]); } 

this works fine @ times, of times piece of code going infinite loop,the 'scanf' in loop accepting values infinitely,i tried using function (fflush) clear buffer contents,but still not working, please me out!! , please explain why !!

the code posted cannot enter infinite loop, it's probable scanf() function blocking until input ctrl+d end input stream or maybe integer, problem handling input in dangerous way because not checking errors @ all, might want this

#include <stdio.h> #include <stdlib.h>  #define clearstdin() {int chr; while (((chr = getchar()) != eof) && (chr != '\n')); } while (0) #define somelargesize 1024  int main(void) {     unsigned int index;     unsigned int size;     int          result;      fprintf(stderr, "input desired array size: ");     while (((result = scanf("%u", &size)) != 1) && (result != eof))      {         fprintf(stderr, "invalid input, try again\n");         clearstdin();      }     if (result == eof)      {         fprintf(stderr, "eof recieved, ending program\n");         return -1;      }     if (size < somelargesize)      {         int array[size];          (index = 0 ; index < size ; index++)          {             fprintf(stderr, "input integer: ");             if (((result = scanf("%d", &array[index])) == 1) && (result != eof))                 fprintf(stdout, "\tarray[%d] = %d\n", index, array[index]);             else if (result == eof)              {                 fprintf(stderr, "eof recieved, ending program\n");                 return -1;              }             else              {                 fprintf(stderr, "invalid input, try again\n");                 index -= 1;              }             clearstdin();          }      }     else      {         fprintf(stderr, "sorry, requested large array\n");         return -1;      }     return 0; } 

the problem program above, if input white space character while scanf() wating input nothing, until valid or invalid input non-white-space input entered.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -