Array Input Problem

I want to input an integer array in C in which each element that user enters is space delimited and size of array is not known for eg 1 2 3 4 5 array should contain 1 2 3 4 5 till user presses enter after 5 can anyone help me plzz?

Knowledge of dynamic allocation like malloc() , calloc() and realloc() will be fine for this type of situation.But it take more time because it allocates space at run time.

int main()

{

int *arr,c=1,i=0,j=1;

arr = (int*)malloc(sizeof(int));

printf("enter array : ");

while(c!=’\n’)

{

scanf("%d",&c);    //read the input from keyboard standard input

//re-allocate (resize) memory for integer read to be stored

arr = (int*)realloc(arr,j*sizeof(arr));

arr[i] = c;  //store read integer by making pointer point to c

i++;
j++;

}

free(arr); //important step the pointer declared must be made free

return 0;

}
I think above code will help you.

1 Like

i have read a simpler solution than this somewhere whats ur take on it? the code goes like this

int count,a[50],i=0;

while((count=getchar())!=10&&i<50)//10 is ascii value of line feed
{
a[i++]=count-‘0’;
}

In your questions there are two things you have to master.

  1. Stop reading new numbers as soon as newline is pressed

  2. storing integers without knowing their number in advance.

There a quite some possibilities to achieve this, but you have to understand which restrictions apply. deepakmourya gave you a solution in C for the second problem ((input wont at newline since scanf just reads over this whitespace).
Your solution has two limitations:

a) You can only read one-digit integers

b) You can read at most 50 of them (in deepakmourya’s solution the amount is only bounded by memory)

the important part of a C++ solution for 1) and 2) would look something like this:

vector<int> numbers;
char x=' ';
int y;
cin>>noskipws;  //dont run over whitespace in input
while(x!='\n'){  //stop if newline is read
cin>>y;
numbers.push_back(y);
cin>>x;
}

Of course also for this program some restrictions must apply:

  • The numbers may not be larger than the maximal integer value

  • input has to be correctly formatted with exactly one space in between the numbers

1 Like

thanks for the help

what’s noskipws?

You could use the return value of scanf.

Scanf returns number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned.

code : ideone

thanks for answering but ur solution is not working i have run ur code in codeblocks.

It’s simple

int c[10000];   //you can declare of any size, the compiler will automatically clean the extra memory
 int i;    

 while(c!=\n)
 {
     scanf("%d",c[i]);
     i++;

 }
1 Like