2

Here's the code that I based here http://www.thecrazyprogrammer.com/2015/02/c-program-count-occurrence-word-text-file.html. (new in c++)

#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;


int main()
{
  // std::cout << "Hello World!" << std::endl;
 // return 0;

 ifstream fin("my_data.txt"); //opening text file
 int count=0;
 char ch[20],c[20];

 cout<<"Enter a word to count:";
 gets(c);

 while(fin)
 {
  fin>>ch;
  if(strcmp(ch,c)==0)
   count++;
 } 

 cout<<"Occurrence="<<count<<"n";
 fin.close(); //closing file

 return 0;

}

Error in Patter Counting

my_data.txt has only 3 "world" in it, but as I run the program, it results to

enter image description here

here's the textfile's content

enter image description here What could go wrong?

DevSolar
  • 59,831
  • 18
  • 119
  • 197
rickyProgrammer
  • 1,049
  • 2
  • 20
  • 56

2 Answers2

2

A solution using std::string

int count = 0;
std::string word_to_find, word_inside_file;

std::ifstream fin("my_data.txt");
std::cout << "Enter a word to count:";
std::cin >> word_to_find;
while (fin >> word_inside_file) {
    if (word_to_find == word_inside_file )
        count++;
}

std::cout << "Occurrence=" << count << "";

If you want to find all occurrences inside other strings as well, as mentioned in the comments, you can do something like this:

...
while (fin >> word_inside_file) {
    count += findAllOccurrences(word_to_find, word_inside_file);
}
...

Inside findAllOccurrences(std::string, std::string) you will implement a "find all string occurrences inside another string" algorithm.

k_kaz
  • 576
  • 1
  • 8
  • 20
  • Hi, this works well, but when i create NO Space in between the words, it no longer read correctly like "worldworldworld" – rickyProgrammer Jan 25 '17 at 10:23
  • because fin >> word_inside_file will read one whole string at a time, which in this case will be worldworldworld which is different string from world. – k_kaz Jan 25 '17 at 10:24
  • right. that's why I use char in my previous sample, is there a way to do it when there's no space? – rickyProgrammer Jan 25 '17 at 10:25
  • You can use std::string::find and std::string::substr but you will have to implement some algorithm there because find only returns the first occurrence. This is a question, find all string occurrences in another string. – k_kaz Jan 25 '17 at 10:31
  • 1
    as per this question, i am accepting this answer. thanks – rickyProgrammer Jan 25 '17 at 10:41
  • Words fundamentally have spaces between them, otherwise words like otherwise might be two words, other and wise, rather than otherwise. If you want to start finding substrings that's a different problem. – doctorlove Jan 25 '17 at 11:06
0

If you are new to c++ you shouldn't really use gets. Read about "buffer overflow vulnerability". gets() is more like c-style. You should consider using std::cin.