0

我使用 istream_iterator 从输入中读取整数(直到 eof)并将它们存储到向量中

之后我想读取一个整数(或者可能是另一种类型的值,例如字符串)。我怎样才能做到这一点?

  • 我应该使用 cin (也许以某种方式“清除”它)?我应该使用已经创建的 istream_iterator 吗?

“有问题的”代码如下。它不使用 cin 读取值。

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

int main(){
// creates two iterators to the begin end end of std input
istream_iterator<int> int_it(cin), eof;

vector<int> int_vec(int_it,eof);


// prints the vector using iterators
cout<<"You gave me the vector: ";
copy(int_vec.begin(),int_vec.end(),ostream_iterator<int>(cout," "));
cout<<endl;

int value;
cout<<"Give me the value you want to search for: ";
cin>>value;

int x=count(int_vec.begin(),int_vec.end(),value);
cout<<"Value "<<value<<" is found "<<x<<" times\n";
}
4

1 回答 1

1

在评论中,您写道:

我想读取向量整数,直到用户按下 ctrl-D (eof)。然后我想重新使用 cin 来阅读其他内容。

你不能这样做。一旦std::cin/stdin关闭,它就无法重新打开以从中读取更多数据。

不过,您可以使用不同的策略。您可以使用不是整数的东西,而不是依赖 EOF 来检测整数向量的输入结束。例如,如果您的输入包括

1 2 3 4 end

然后读取int_vec将在输入流中“结束”的开头停止。然后,您可以使用cin.clear()andcin.ignore()清除流的错误状态并丢弃该行中的其余输入,然后再继续从cin.

您的程序的更新版本

#include <iostream> 
#include <iterator>
#include <algorithm>
#include <vector>
#include <limits>

using namespace std;

int main()
{
   // creates two iterators to the begin end end of std input
   cout << "Input some integers. Enter something else to stop.\n";
   istream_iterator<int> int_it(cin), eof;
   vector<int> int_vec(int_it, eof);

   // prints the vector using iterators
   cout<<"You gave me the vector: ";
   copy(int_vec.begin(),int_vec.end(), ostream_iterator<int>(cout," "));
   cout << endl;

   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   int value = 0;
   cout << "Give me the value you want to search for: ";
   cin >> value;

   int x = count(int_vec.begin(), int_vec.end(), value);
   cout << "Value " << value << " is found " << x << " times\n";
}

控制台输入和输出

Input some integers. Enter something else to stop.
1 2 3 4 end
You gave me the vector: 1 2 3 4
Give me the value you want to search for: 1
Value 1 is found 1 times
于 2019-05-14T19:14:05.327 回答