:
getline(cin,word);
if(word == keyWord)
{
cout << word << endl;
count++;
}
, cin. infile. :
infile >> word;
if(word == keyWord)
{
cout << word << endl;
count++;
}
In addition, you must change the condition of the loop. You do not need to check if infile exists . You must check this before starting the cycle. For the loop, you need to check if the eof state is reached or not:
if ( !infile.is_open() ) {
cerr << "Error while opening file." << endl;
exit( EXIT_FAILURE );
}
while( !infile.eof() ) {
infile >> word;
if(word == keyWord)
{
cout << word << endl;
count++;
}
}
And as you can see, now you can get rid of this strange second if you put it inside the loop.
The final step is to introduce the โread aheadโ technique: it makes no sense to test if we are not reading anything.
if ( !infile.is_open() ) {
cerr << "Error while opening file." << endl;
exit( EXIT_FAILURE );
}
infile >> word;
while( !infile.eof() ) {
if( word == keyWord )
{
cout << word << endl;
count++;
}
infile >> word;
}
Hope this helps.
source
share