get an array of numbers from an input sequence of arbitrary length
Hello all,
How would you go about getting an array of numbers from an input sequence of arbitrary length? i.e. the user can input:
1 -2 3 -4 5 -6 7 -8
I understand dynamic memory allocation, and can think of a way to do this that would involve a lengthy algorithm of looping through and checking for whitespace/(- sign) on either side, but is there a better way to go about it?
thanks!
- iochi
Re: get an array of numbers from an input sequence of arbitrary length
Just use a vector with push_back ... std::vector takes care of
all the re-allocation.
Code:
vector<int> v;
int value;
while (get next number)
{
v.push_back(value);
}
You could use other containers also : std::list , std::deque
Re: get an array of numbers from an input sequence of arbitrary length
Ah I'm sorry, I forgot to mention that this has to be done in C. Will this approach still work? (or is there another way that I have to do it?)
Thanks!
Re: get an array of numbers from an input sequence of arbitrary length
sscanf? and allocate an array of 1 element. If sscanf("%d") succeeds then increase the size of the array with like realloc
Re: get an array of numbers from an input sequence of arbitrary length
sscanf? and allocate an array of 1 element. If sscanf("%d") succeeds then increase the size of the array with like realloc