I need to read numbers from a user and then copy them to an array. This shouldn't be that hard but I think I'm making it hard by trying to use getline and then parsing the numbers. Heck I don't even know how to do that.

Is there an easy way to read a line of numbers and store each number into an array?

Thanks for the help.

9 Years
Discussion Span
Last Post by Ancient Dragon

>>Is there an easy way to read a line of numbers and store each number into an array?
Yes -- juse use cin's >> operator to get each individual number

int i = 0;
int array[255];
while( cin >> array[i] )

you can also use stringstream class in conjunction with getline()


what would i do if i didn't know the size of the array until after it was read in? Is there a way to make a dynamic array?


you've been a great help. Thanks.

If you have time, what would that look like just using an array? I know it's probably overkill but I'm interested.


you would have to use new operator to allocate the array size, or you could create a linked list of integers. Something like this -- warning: not compiled or testes. As you can see its a lot easier, safer, and less coding to use std::vector.

const int blocksize = 10;
int asize = 0;
int cur = 0;
int* matrix = 0;
int n;
while( cin >> n)
   if( cur == asize )
   // if matrix is full, we need to realocate with more space
      // allocate new temp array
      int* newm = int[asize+blocksize];
      // copy old matrix to new matrix
      for(int i = 0; i < asize; i++)
        newm[i] = matrix[i];
      // delete old matrix
      delete[] matrix;
      // set pointers
      matrix = newm;
      // bump matrix size
      asize += blocksize;
   matrix[cur++] = n;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.