我正在阅读 The C++ Programming Language Book 并到达“Iterators and 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';
}
我完全理解,现在我正在玩这个例子,使它也适用于数字。我尝试在相应的地方添加以下内容...
istream_iterator<int>jj(cin);
int i1 = *jj;
cout <<s1 << ''<< s2 << ''<< i1 <<'\n';
这不会让我在运行程序时有机会输入数字部分。为什么会这样?迭代器只能在
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';
}
以上适用于
你好,世界
或者
你好
世界
将 Hello World 作为输出。
删除评论
istream_iterator<int>dd(cin);
int d = *dd;
并注释掉
int d =24;
导致 Hello Hello 0 作为输出。
最佳答案
当您第一次创建 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';
}
这是您想要执行的操作:
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';
}
关于c++ - 使用 istream_iterator 迭代 int 和 string,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4160651/