Reading In A Variable Amount Of Interger Input

How can I read in a different amount of integers based on a users input.

Enter Amount of Integers : 3

I Then allocated memory with malloc to hold 3 integers.  Now I want to enter in three integers.  How can I do this with scanf or is therea better way.

I tried using a for loop with the scanf, but it did not work as expected.
      printf("\nPlease Provide %d chainwheel sizes in ascending order: ", iNumberChainWheels );

for ( iLoopVariable = 0 ; iLoopVariable <  iNumberChainWheels; iLoopVariable++ )
scanf("%d",&pChainWheelSizes[iLoopVariable]) ;

The above code did call scanf three times, but what if the user entered all tree integers on the same line...  Any thoughts.

Who is Participating?
mlaiosaConnect With a Mentor Commented:
When you use the standard input rutines, some crazy buffering will be used.  When you run scanf, it will begin processing the things you asked for (the string whcih is the first parameter).  If the buffer becomes empty before it is done, it will have the user enter chartcers (into the buffer) untill return is pressed, then continues processing the buffer.

If all the ints are entered on the same line, only the first one will be processed by the first scanf (which is what gets the keyboard input), the rest will remain in the buffer.  Next time you call scanf, no input will be requested becaouse the required data is already in the buffer.

Try it out:

#include <stdio.h>

void main ()
  int n;
  printf("\nHow many integers? ");

  int* a=new int[n];

  for ( int i = 0 ; i < n; i++ )

  printf("Here they are:\n");

  for ( i=0; i<n; i++ )
    printf("%2d: %d\n",i+1,a[i]);

What was unexpected about what it did when the user entered all tree integers on the same line?
larockdAuthor Commented:
Thank you for taking your time to answer this.  Everything worked perfect. I also appreciate the explanation on the buffering.,.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.