number of occurrences

My program is supposed to read the number of occurrences of a word from a text file but it doesn't work and i don't know what's wrong with it.

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

int main()
{
ifstream fin("words.txt");
int count=0;
char ch[20],c[20];


gets(c);

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

cout<<count<<;
fin.close(); //closing file

return 0;

}
What does the input file contain?
Why don't you use strings?
Why this hotchpotch of C and C++ ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
#include <string>
#include <cstring> // strerror
#include <cerrno> // errnp

using namespace std;

int main()
{
  ifstream src("input.txt");
  if (!src)
  {
    cerr << strerror(errno) << "\n";
    return errno;
  }
  string needle;
  cout << "Name to search for: ";
  cin >> needle;
  string word;
  int count = 0;
  while (src >> word)
    if (needle == word)
      count++;

  cout << "The word " << needle << " occurs " << count << " times." << "\n\n";
}
1. Check that your file actually opened. Yes, really!
2. Use std::string rather than c-strings; you already have a #include <string> header. If you insist on using c-strings then you would need #include <cstring> here for strcmp().
3. cout<<count<<; is an extremely odd (and wrong) line.
4. "it doesn't work" is not a helpful description of the problem. Actually, it doesn't compile.
5. Please use code tags. Then we can test the code with c++ shell rather than having to download and re-format it.
6. Tell the user that you require input. Don't just use gets(c) and expect him to remember.
Topic archived. No new replies allowed.