0

In C, i write this easy function. I would know if i could stop the array filling before (for example if it has rank : 5 , i would stop the scanf filling when i press enter on my keyboard)

void input_array(int a[], int n){
   int i;
   for (i = 0; i < n ; i++)
      scanf("%d", &a[i]);
  }
LITTORIO
  • 1
  • 1
  • 2
    You may want to read about [Disadvantages of scanf](https://stackoverflow.com/questions/2430303/disadvantages-of-scanf). – Amadan Jul 06 '21 at 08:08
  • Just enter the data all on one line and then press Enter once. There is no relation between the coding of `scanf` and the act of providing data - it just looks in the input buffer. But do you mean you want to input *fewer* than `n` items? – Weather Vane Jul 06 '21 at 08:37
  • Not sure what you mean by "if it has rank: 5" – Edgen Jul 06 '21 at 08:41
  • 3
    Ask the user how many (up to `n`) and change the function from `void` to `int` so that the caller knows how many. Or input with `fgets` and `sscanf` and terminate on the empty (newline only) string. – Weather Vane Jul 06 '21 at 08:48
  • Completely with @WeatherVane on this one! – Sorenp Jul 06 '21 at 08:56
  • @LITTORIO - If you _stop the array filling before_, how shall the caller know how many numbers have been entered? – Armali Jul 06 '21 at 16:58

1 Answers1

0

This will work for you. Code is a bit tacky but you'll get the idea

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int convert (char * input, int * number){
    int result = 0 ;
    int i ;
    for (i = 0; i < strlen(input) && result == 0; i++) {
      if (!isdigit(input[i])) {
           result = -1 ;
       }
    }
    if (result == 0)    {
        sscanf(input, "%d", number);
    }

    return result ;
}

int input_array(int a[], int n){
   int i;
   int j;
   int len = 30 ;
   char value[len] ;

   for (i = 0; i < n ; i++) {
        fgets(value, len, stdin) ;

        // get rid of cr/lfs
        for (j = 0; j < strlen(value); j++){
            switch (value[j]) {
                case '\r' :
                case '\n' :
                  value[j] = 0 ;
                break ;
            }
        }

        if (strlen (value) == 0) return i ; // return number of entries

        if (convert(value, &a[i]) == -1) {
            return -1 ;
        }
    }

    return (n) ;
}

int main(){
    int arr[6] ;
    int entries ;

    entries = input_array (arr, 6) ;
    if (entries <= 0) {
        printf ("Bad data entered\n") ;
    }
}

Edgen
  • 69
  • 7
  • Sorry, screwed up the code. (Dumb cut and paste error and it didn't return the number of entries - only saw your comment afterwards) – Edgen Jul 06 '21 at 09:38