Hi everyone,

I'm trying to store user input into an array.
The output looks like this:

Enter the size of the arrays:
5

Enter the cells of array1:
1 2 3 4 5

Enter the cells of array2:
5 4 3 2 1

This is my code so far:

int main() {

  int size, eleOne, eleTwo;
  int i=0, j=0;

  printf("Enter the size of the arrays: \n");
  scanf("%d", &size);
  int array1[size];
  int array2[size];
  int c = getchar();

  printf("Enter the cells of the first array: \n");
  while ((i < size-1) && (c != EOF)) {
    array1[i] = c;
    i++;
    c = getchar();
  }

  printf("Enter the cells of the second array: \n");
  while ((i < size-1) && (c != EOF)) {
    array2[j] = c;
    j++;
    c = getchar();
  }
}

First of all, the numbers can be any length. If the input is size 5, the cells could be "500000 500000000 123232 23232323 5000000". The space of course tells us the number has ended and that the number needs to be stored in the first cell of the array, but I am not sure how to program that. Any ideas? Thanks very much!

Not really sure what you program's purpose is, are you trying for something like below?

#include <stdio.h>

int main() 
{
  int i = 0, size = 0;

  printf("Enter the size of the arrays->");
  scanf("%d", &size);
  
  int array1[size];
  
  for (i = 0; i < size; ++i)
  {
    fprintf(stdout, "Enter element[%d]->", i);
    fscanf(stdin, "%d", &array1[i]);
  }

  for (i = 0; i < size; ++i)
    fprintf(stdout, "element[%d]->%d\n", i, array1[i]);

  return 0;
}

Here's what I'm trying to do: The user enters a size, an integer, and then I create 2 arrays of that size. Let's say that number is 5. The user then enters 5 digits, which will be placed in the 5 cells of the first array. Then the user enters another 5 digits, for the second array. Those digits will be stored in the second array.

I need to make a[0] = the first number that the user input. a[1] = second number, a[2] = third..etc. There are a bunch of other calculations I need to make but I need to get this part working first.

Thanks for any further help. :D

This article has been dead for over six months. Start a new discussion instead.