Iterate over int and string using istream_iterator

I am reading a book of C ++ programming languages ​​and went to β€œIterators and I / O” on page 61, they give the following example to demonstrate repetition through the line presented.

#include <iostream>
#include <iterator>
#include <string>

using namespace std;

int main()
{

    istream_iterator<string>ii(cin);
    istream_iterator<string>eos;

    string s1 = *ii;
    ++ii;
    string s2 = *ii;

    cout <<s1 << ' '<< s2 <<'\n';
}

What I fully understand, now I played with this example to make it work for numbers as well. I tried to add the following in appropriate places ...

istream_iterator<int>jj(cin);
int i1 = *jj;
cout <<s1 << ''<< s2 << ''<< i1 <<'\n';

Which does not give me the opportunity to enter the number section when starting the program. Why is this so? Is it possible to use an iterator only once per cin? such that it already has input from cin, so the next iterator is ignored?


Change this is what I got after pasting

#include <iostream>
#include <iterator>
#include <string>

using namespace std;

int main()
{

    istream_iterator<string>ii(cin);
    istream_iterator<string>eos;

    //istream_iterator<int>dd(cin);

    string s1 = *ii;
    ++ii;
    string s2 = *ii;
    //int d = *dd;
    int d =24;
    cout <<s1 << ' '<<s2<<' '<<d<< '\n';
}

Above work for

Hello world or
hello
world

Hello World .

istream_iterator<int>dd(cin);
int d = *dd;

int d =24;

Hello Hello 0.

+3
1

istream_iterator, . , ++. , :

int main()
{

    istream_iterator<string>ii(cin);  // gets the first string "Hello"
    istream_iterator<int>jj(cin); // tries to get an int, but fails and puts cin in an error state

    string s1 = *ii; // stores "Hello" in s1
    ++ii;            // Tries to get the next string, but can't because cin is in an error state
    string s2 = *ii; // stores "Hello" in s2
    int i1 = *jj;    // since the previous attempt to get an int failed, this gets the default value, which is 0

    cout <<s1 << ' '<<s2 <<' '<< i1 << '\n';
}

:

int main()
{

    istream_iterator<string>ii(cin);

    string s1 = *ii;
    ++ii;
    string s2 = *ii;

    istream_iterator<int>jj(cin);
    int i1 = *jj;

    // after this, you can use the iterators alternatingly,
    //  calling operator++ to get the next input each time

    cout <<s1 << ' '<<s2 <<' '<< i1 << '\n';
}
+6

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


All Articles