我想在使用 istream 运算符读取输入后使用 cin

I want to use cin after read input with istream operator

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

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

"problematic"代码如下。它不使用 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";
}

您在评论中写道:

I want to read vector integers until the user press ctrl-D (eof). Then i want to re-user the cin for reading other stuff.

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

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

1 2 3 4 end

然后对 int_vec 的读取将停止在输入流中 "end" 的开始处。然后,您可以使用 cin.clear()cin.ignore() 清除流的错误状态并丢弃行中的其余输入,然后继续从 cin.[=20= 读取更多内容]

您程序的更新版本

#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