Home > OS >  How can I read only numbers from an input with scanf?
How can I read only numbers from an input with scanf?

Time:03-09

Implement a function that receives an array of integers and its capacity and fills the array with all the values read from the keyboard which are prime numbers, without overflowing the array. The keyboard input might consist of other data (words) that are to be ignored. Return the numbers of elements copied into the array. Also, provide an adequate main().

  #include <stdio.h>
    int fills(int arr[], int cap)

    {
    int element, flag=0,i=0,sec;
      while(scanf("%d", &element)==1 && i<cap)
        {
            printf("%d", element);
        sec=element;
       // printf("%d\n", sec);
          for(int j=2;j<sec/2;j  )
          {
              if(sec%j==0)
               flag=1;
          }
          if(flag==0)
          {
              arr[i]=element; 
              i  ;
          }
        // printf("%d\n", arr[i-1]); 
         sec=0;
         
    }
    for(int k=0;k<i;k  )
    {
        printf("%d ", arr[k]);
    } 

}
   

     int main()
        {
            int arr[4], cap=4;
            fills(arr, cap);
            return 0;
        }

This is my code so far, but I can't skip the words or the others elements

CodePudding user response:

You could read strings from the input, detect whether the string you read consists of only digits, and then decide what to do with it: whether you convert the string into an integer, or simply disregard it.

CodePudding user response:

A robust solution is to ignore any offending input when you try to read integers. For example:

/* read an integer value from fd ignoring any offending character
 * Parameters:
 * fd: FILE to read
 * err pointer to an integer which is set to 1 if a read error is encountered
 */
int getint(FILE* fd, int *err) {
    int i, cr;
    while ((cr = fscanf(fd, "%d", &i)) == 0) {   // can we read an int?
        if (fgetc(fd) == EOF) { // if no skip one character and test error condition
            if (err != NULL) {                   // set err if pointer is not NULL
                *err = 1;
            }
            return -1;                           // and return -1
        }
    }
    if (cr != 1) {                               // a possible fatal read error?
        if (err != NULL) {                       // same handling as above
            *err = 1;
        }
        return -1;
    }
    return i;                                    // Ok return the integer value
}
  •  Tags:  
  • c
  • Related