0

I am trying to search for a word in a file, and each time it appears it increases the count by 1. The file currently has multiple lines with the word Culture in it. The program outputs 1 for each time it runs.

int main()
{
  fstream plate("data.txt", ios::in | ios::out | ios::app);
  int count = 0;
  string search = "Culture";
  string temp;
  while(!plate.eof())
    {
      getline(plate, temp);
      if(temp == search)
        {count++;}
    }

  cout << count << endl;    

  return 0;
}

I don't see why it only outputs 1 every time

  • 1
    Relevant read on `while(!plate.eof())`: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – Azeem Apr 30 '20 at 04:57

2 Answers2

2

You are reading the file line-by-line, comparing whole lines not individual words, counting only the lines that exactly match the search string from the beginning to the ending of each line.

Try this instead:

int main() {
    ifstream plate("data.txt");
    int count = 0;
    string search = "Culture";
    string temp;
    while (plate >> temp) {
        if (temp == search) {
            ++count;
        }
    }
    cout << count << endl;
    return 0;
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
1

The problem is, you are comparing the whole line with the key, therefore counter increases whenever the whole line equals the word. Instead, try to check if the line contains the word.

if (temp.find(search) != std::string::npos) {
    // contains the word
    count++;
}

Update: If the word may appear in each line more than once, then you need to consider using another loop:

int step = search.size();
int position = 0;

while((position = temp.find(search, position)) != std::string::npos) {
    position += step;
    count++;
}
Amir MB
  • 1,127
  • 5
  • 10
  • What exactly does the std::string::npos line do? I added it and it started working, so thank you – ADS_Fibonacci Apr 30 '20 at 05:44
  • `std::string::npos` is a magic constant (typically -1 I believe) that means "no match found." – mukunda Apr 30 '20 at 05:50
  • This code does not take into account the possibility of the `search` term being a substring of a larger word. For example, searching for `Cult` would count instances of `Culture`. The code should be doing whole-word searches, not substring searches. – Remy Lebeau Apr 30 '20 at 06:15