gpt4 book ai didi

c++ - istream_iterator 行为

转载 作者:行者123 更新时间:2023-11-28 00:57:46 25 4
gpt4 key购买 nike

我有两段代码。它们在 main() 中单独使用时可以正常工作。

vector<int> v;

cout << "Enter sequance of integers "<< "(press q to quit) : ";
istream_iterator<int> start_cin(cin);
istream_iterator<int> end_of_cin;
copy(start_cin,end_of_cin,back_inserter(v));

for ( vector<int>::iterator It = v.begin();It != v.end(); It++ )
cout << *It << "\t";
cout << endl;

vector<string> vS;
cout << "Enter three strings : ";
for ( int i = 0; i < 3; i++ )
vS.push_back(*istream_iterator<string>(cin));

ostream_iterator<string> sIt(cout,", ");
copy(vS.begin(),vS.end(),sIt);
cout << endl;

当这两部分一起使用时,即

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <string>
using namespace std;

int main ()
{
// first part

vector<int> v;

cout << "Enter sequance of integers "<< "(press q to quit) : ";
istream_iterator<int> start_cin(cin);
istream_iterator<int> end_of_cin;
copy(start_cin,end_of_cin,back_inserter(v));

for ( vector<int>::iterator It = v.begin();It != v.end(); It++ )
cout << *It << " \t";
cout << endl;


vector<string> vS;
cout << "Enter three strings : ";
for ( int i = 0; i < 3; i++ )
vS.push_back(*istream_iterator<string>(cin));

ostream_iterator<string> sIt(cout,", ");
copy(vS.begin(),vS.end(),sIt);

cout << endl;

return 0;
}

此处第一部分有效,但第二部分给出输出:Enter Three Strings : , , ,。我想知道这种行为背后的原因是什么?

谢谢。

最佳答案

copy()完成后,cin会处于不可读状态(!cin.good()),由于读取“整数”q 失败。这意味着后续的 for 循环将无法读取任何内容。

添加:

cin.clear();
cin.ignore(); // To skip the unread "q"

for 循环之前。

编辑:

正如 James Kanze 评论的那样, 检查以确保 "q"copy() 终止的原因:

...

cin.clear();
string int_read_terminator;
cin >> int_read_terminator;
if ("q" != int_read_terminator)
{
cerr << "Integer copy() failure: " << int_read_terminator << "\n";
}
else
{
...

关于c++ - istream_iterator 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10171511/

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