0

Possible Duplicate:
How to read arbitrary number of values using std::copy?

Hello. I'm reading nums from file. I do it with std::copy

copy(istream_iterator<int>(input_file), 
       istream_iterator<int>(), 
       back_inserter(first));

But this function copy only whole file, although I want to copy only N symbols. Thanks.

Community
  • 1
  • 1
dark
  • 167
  • 1
  • 6
  • 17

1 Answers1

0

SGI's STL reference is quite good. The second argument needs to be the number of items you want to read.

Update

(After changing your initial post, which used copy_n)

You can use a simple loop to do what you want, as in

template <typename Input, typename Output>
Output copy_n (Input i, size_t N, Output o)
  {
    for (; N > 0; --N)
      {
        *o = *i;
        ++i;
        ++o;
      }
    return o;
  }
Community
  • 1
  • 1
dennycrane
  • 2,301
  • 18
  • 15
  • There is typo in first message. I use the function std::copy, not std::copy_n. But I can't use std::copy_n, because I have old compiler - Microsoft Visual C++ 2003 – dark Nov 28 '10 at 12:51
  • "This function is an SGI extension; it is not part of the C++ standard." – icecrime Nov 28 '10 at 12:53
  • 1
    The OP used it originally in his first post. – dennycrane Nov 28 '10 at 12:57
  • It is also part of the new standard (but could be implemented on your own easily as shown) http://www2.research.att.com/~bs/C++0xFAQ.html#algorithms – hansmaad Nov 28 '10 at 13:10
  • If you're reading a stream, `copy_n` might not be right anyway. Depends whether "I want to copy only N symbols" means, "I want to copy exactly N symbols", or "I want to copy as many symbols as are in the file up to a maximum of N". – Steve Jessop Nov 28 '10 at 13:31
  • 5
    @DennyCrane: Your code is flawed, what happens if the iterator reaches end before N increments have been encountered? Shouldn't you break out of the loop? should end also be passed in? –  Nov 28 '10 at 23:31
  • @Beh Tou Cheh: That depends on what that code promises to do. If it is *copy exactly n elements* then why should everyone adhering to that promise pay for everyone who fails to give input that has n elements in the first place. If, OTOH, the promise is *copy up to n elements*, which is, as @Steve Jessop noted, more sensible in this case, then you're right of course. This would conflict with the expectation people grew accustomed to when they see the identifier `copy_n`, so another name should then be chosen. I guess I got locked on that `copy_n` track since OP originally used `copy_n`. – dennycrane Nov 28 '10 at 23:56