gpt4 book ai didi

c++ - 使用 istream_iterator 遍历 int 和 string

转载 作者:太空狗 更新时间:2023-10-29 20:31:31 26 4
gpt4 key购买 nike

我正在阅读 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
你好
世界

将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com