tez
tez

Reputation: 5300

Reusing std::cin after EOF

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.

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;

}

The final output I get is "Your word appeared 0 times". What is the problem with the code. Any help would be great.

Upvotes: 3

Views: 3807

Answers (3)

wallyk
wallyk

Reputation: 57774

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;

Upvotes: 3

Jay D
Jay D

Reputation: 3307

http://www.cplusplus.com/forum/articles/6046/

Read this as an example and probable issues !!

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

while (cin>>x) 
{
    words.push_back(x);
}

Here, you're reading until failure. So, when this loop finishes, cin is in an error state. You need to clear the error state:

cin.clear();

Upvotes: 2

Related Questions