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.

>>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] )
   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?

use a vector

#include <vector>

int main()
{
    vector<int> ay;
    int n;
    while( cin >> n)
       ay.push_back(n);
}

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.