CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jun 2009
    Posts
    63

    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

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    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

  3. #3
    Join Date
    Jun 2009
    Posts
    63

    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!

  4. #4
    Join Date
    Mar 2004
    Posts
    235

    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
    01101000011001010110110001101100011011110010000001110011011001010111100001111001

  5. #5
    Join Date
    Mar 2004
    Posts
    235

    Re: get an array of numbers from an input sequence of arbitrary length

    sscanf? and allocate an array of 1 element. If sscanf("&#37;d") succeeds then increase the size of the array with like realloc
    01101000011001010110110001101100011011110010000001110011011001010111100001111001

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured