-1

I have to input an array of integers. The length of this array is determined at runtime when the user hits some sentinal key (likely I'll use return)

EXAMPLE

//input path to be analyzed
  int n = 0;
  while(scanf("%d",&input[n])==1){
    //??
  }
}

Input:

3 2 1 3 4 5 (return)

Then these values are stored in the array a as:

[3, 2, 1, 3, 4, 5]

I also need proper error checking of course.

This is a basic problem im sure however I'm unable to solve it.

Thanks!

Im thinking ill need a while loop however im unsure how to use scanf to both terminate the loop, initilize the array and input the values.

Nick Steeves
  • 3
  • 2
  • 4
  • 3
    Solve one problem at a time. Put together a loop that repeatedly reads integers until an EOF or other termination condition happens. Storing them is an *extension* of that algorithm, but that algorithm has to be done *first*. Once that works, *then* worry about sizing up a dynamic sequence to store them in as they are read. – WhozCraig Jan 21 '19 at 00:27
  • 2
    If you want to use newline as a sentinel, you can't use `scanf()` sensibly. You need to read the lines separately ([`fgets()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) or POSIX [`getline()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html)) and then process the string with [`sscanf()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html). All the numeric conversion specifications in `scanf()` format strings blithely skip white space, including newlines. – Jonathan Leffler Jan 21 '19 at 02:37
  • 1
    Welcome to Stack Overflow, by the way. Please read the [About] and [Ask] pages soon, and also the one about how to create an MCVE ([MCVE]). Consider how you'd store the numbers returned by successive calls to `rand()` in a loop — that same mechanism can be adapted to deal with reading and storing numbers. It's not very hard with `malloc()` et all — but it isn't entirely straight-forward. If you show honest attempts to solve either problem and find yourself stuck, then explain what your trouble is and show the code, and you'll probably get help. Simply asking for code doesn't work. – Jonathan Leffler Jan 21 '19 at 02:42
  • 1
    There is no builtin function to read an arbitrary amount of data and allocate memory to store it. One solution is to write a loop using `realloc` that increases the allocation size as you sucessfully read another item – M.M Jan 21 '19 at 02:45
  • [scanf unknown number of integers, how to end loop?](https://stackoverflow.com/q/52937192/2410359) may help. – chux - Reinstate Monica Jan 21 '19 at 07:02

1 Answers1

2

You can do it as follows:

int main()
{
    char ch;
    int i=0;
    int input[100000]; //Or dynamically allocate
    while(scanf("%c",&ch) && (ch!='\n')){
    if(ch==' ') continue;
    input[i++]=ch - '0';
    printf("%d ",input[(i-1)]);
}
}