Istream_iterator: getting additional input

I can't get this blasted job to work correctly. The problem is that if I want to enter 2 numbers, I really need to enter 3. What is wrong?

namespace MT
{
    template<class IIT, class OIT>
    OIT copy_n(IIT iitBegin, size_t szCount, OIT oitBegin)
    {   
        for(size_t szI = 0; (szI < szCount); ++szI)
        {   
            *oitBegin++ = *iitBegin++;
        }   

        return oitBegin;
    }   
};

int main()
{
    vector<int> vNumbers;
    vector<char> vOperators;
    int iNumCount = 0;
    int iNumOperators = 0;

    cout << "Enter number of number(s) :) :\n";
    cin >> iNumCount;
    cout << "Enter number of operator(s) :\n";
    cin >> iNumOperators;

    int iNumber;
    cout << "Enter the " << iNumCount << " number(s):\n";
    MT::copy_n(istream_iterator<int>(cin), iNumCount, back_inserter(vNumbers));

    char cOperator;
    cout << "\nEnter the " << iNumOperators << " operator(s):\n";
    MT::copy_n(istream_iterator<char>(cin), iNumOperators, back_inserter(vOperators));

    copy(vNumbers.begin(), vNumbers.end(), ostream_iterator<int>(cout, " "));
    cout << endl;
    copy(vOperators.begin(), vOperators.end(), ostream_iterator<char>(cout, " "));
    cout << endl;

    return 0;
}
+3
source share
3 answers

Change the loop of the stream iterator:

    for(size_t szI = 0; (szI < szCount); ++szI)
    {   
        *oitBegin = *iitBegin;
        if (szI < szCount - 1)
        {
          ++oitBegin;
          ++iitBegin;
        }
    }   
+3
source

The problem is that it istream_iteratoris not read when it is dereferenced, but when it grows:

  • The first value is read during construction istream_iterator
  • Additional iNumCount values ​​are read by copy_n when the iterator is incremented.

, iiBegin++, , . "", (, , ).

[EDIT] :

template<class IIT, class OIT>
OIT copy_n(IIT iitBegin, size_t szCount, OIT oitBegin)
{   
  *oitBegin++ = *iitBegin;
  for(size_t szI = 0; (szI < szCount - 1); ++szI)
    *oitBegin++ = *++iitBegin;
  return oitBegin;
}
+2

I think the problem is that you are not passing an EOF character. If you are working under Linux, try entering CTRL + D after inserting the second number (under Windows it should be CTRL + Z, but I'm not sure).

0
source

Source: https://habr.com/ru/post/1774355/


All Articles