使用istream_iterator迭代int和string

phw*_*hwd 3 c++

我将通过C++编程语言手册并到达"迭代器和I/O"第61页,他们给出了以下示例来演示迭代提交的字符串.

#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';
}
Run Code Online (Sandbox Code Playgroud)

我完全理解,现在我正在玩这个例子,使它也适用于数字.我尝试在各自的地方添加以下内容......

istream_iterator<int>jj(cin);
int i1 = *jj;
cout <<s1 << ''<< s2 << ''<< i1 <<'\n';
Run Code Online (Sandbox Code Playgroud)

这使我没有机会在运行程序时输入数字部分.为什么会这样?迭代器只能使用一次cin吗?这样它已经有输入,cin所以忽略下一个迭代器?


这里编辑是我插入后的内容

#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';
}
Run Code Online (Sandbox Code Playgroud)

以上工作原理

Hello World
Hello
World

给Hello World作为输出.

删除评论

istream_iterator<int>dd(cin);
int d = *dd;
Run Code Online (Sandbox Code Playgroud)

和评论

int d =24;
Run Code Online (Sandbox Code Playgroud)

导致Hello Hello 0作为输出.

Ben*_*ley 6

首次创建istream_iterator时,它会获取第一个输入并在内部存储数据.为了获得更多数据,您可以调用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';
}
Run Code Online (Sandbox Code Playgroud)

这是你想要做的:

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';
}
Run Code Online (Sandbox Code Playgroud)