我不太确定我认为我的根本问题是如何工作的。我已经阅读了之前关于 while(cin>>x) 的几篇文章,但似乎没有什么能真正回答我的问题。我正在使用这个循环来读取一些文本数据:
while (cin >> x){
searchText.push_back(x);
}
但后来在代码中,我试图用一个单词阅读:
cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;
但是上面的while循环/ eof似乎破坏了第二个代码片段(如果我将第二个代码片段移到上面它一切正常,但显然这不是我想要做的)
编辑 为了清楚起见,这是完整的代码:
int main()
{
// ask for the target word
// cout << "Please enter your target word: ";
// string targetWord;
// cin >> targetWord;
// ask for and read the search text
cout << "Enter the complete search text, "
"followed by end-of-file: ";
vector<string> searchText;
string x;
while (cin >> x){
searchText.push_back(x);
}
// check that some text was entered
typedef vector<string>::size_type vec_sz;
vec_sz size = searchText.size();
if (size == 0){
cout << endl << "You must enter some text. "
"Please try again." << endl;
return 1;
}
// ask for the target word
cin.clear();
cout << "";
cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;
int count = 0;
for (int i=0; i<size; ++i){
if (targetWord == searchText[i]){
count++;
}
}
cout << "The target word [" << targetWord << "] was "
"in the search text " << count << " times." << endl;
return 0;
}
我只是想从用户那里获取一些文本......然后是一个搜索词,看看这个词在输入的文本中出现了多少次(很简单!)
我知道我可以做不同的事情,但这里的问题更多是关于如何在之前有 EOF 之后再次使用 cout/cin 流