在EOF之后重用std :: cin [英] Reusing std::cin after EOF
问题描述
下面的代码用于在 std :: vector
中存储一组单词,并计算用户给定的特定单词在向量中出现的次数
The code below is for storing a group of words in a std::vector
and to count how many times a particular word given by the user appears in the vector by comparing it to all the words stored in the vector.
控制台不会在第二个 std :: cin>>>提示输入;
The console does not prompt me for input at the second std::cin >>
in the program below.
#include <iostream>
#include <ios>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[])
{
cout<<"enter your words followed ny EOF"<<endl;
vector<string> words;
string x;
typedef vector<string>::size_type vec_size;
vec_size size;
while (cin>>x)
{
words.push_back(x);
}
size=words.size();
cin.clear();
//now compare
cout<<"enter your word:"<<endl;
string my_word;
int count=0;
cin>>my_word; //didn't get any prompt in the console for this 'cin'
for (vec_size i=0; i<size; ++i)
{
my_word==words[i]?(++count):(count=count);
}
cout<<"Your word appeared "<<count<<" times"<<endl;
return 0;
}
我得到的最终输出是你的单词出现0次。
代码的问题是什么。任何帮助将是巨大的。
The final output I get is "Your word appeared 0 times". What is the problem with the code. Any help would be great.
推荐答案
程序读取单词列表直到文件结束。因此,在终端上,您可以键入EOF字符(在Linux上为 Ctrl-D ,在Windows上为 Ctrl-Z Return 那么?
The program reads the word list until end of file. So, at a terminal, you can type the EOF character (Ctrl-D on Linux, Ctrl-Z Return on Windows), but what then?
我认为在重置流之后,终端将继续读取。但是如果程序正在从磁盘文件,管道等输入,没有希望。文件结束是永远的。
I think after resetting the stream, a terminal will continue to read. But if the program is taking input from a disk file, pipe, etc., there is no hope. End-of-file is forever.
而是使用某种哨兵,或者用计数前缀。这样,第一个循环可以运行,直到列表的逻辑结束。然后它可以读取用于汇总逻辑的词。
Instead, use some sort of sentinel, or prefix it by a count. That way the first loop can run until the logical end of the list. And then it can read the word intended for the summary logic.
while (cin>>x && x != '*') // The word "*" ends the list of words
{
words.push_back(x);
}
size=words.size();
//now compare
cout<<"enter your word:"<<endl;
这篇关于在EOF之后重用std :: cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!