当您第一次创建IStream_迭代器时,它会得到第一个输入并在内部存储数据。为了获得更多的数据,您可以调用operator++。下面是代码中发生的事情:
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';
}