Hi ! I need help here , my program is reading a text file and finding how many the word "The" in it ,but our instructor want it to be counted even if there is no space before it or after it , and i wrote this program but it only read the word "The" if before it and after it a space , so I'll be thankful if someone helps me with it =).
Here is some code to help you. Makes sure you know exactly what it is doing and why it is doing it before you use it!!! Also there is something wrong with this code that you will need to fix that I added in there on purpose. It also isn't complete I left out the hard part for you to figure out :)
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
ifstream file("YourFileName.txt");
` // Vector will holds each word of the file. String will be the temp holder
// for each word.
vector<string> words;
string word;
int counter = 0;
// Reads each word from the file and converts it to lowercase
// then adds that word into the vector.
while (file >> word)
{
for (auto i = 0; i != word.size(); ++i)
word[i] = tolower(word[i]);
words.push_back(word);
}
// Goes through each element in the vector and searches that word
// for "the" if it finds it it will add 1 to the counter.
for (auto i = 0; i != words.size(); ++i)
{
unsigned found = words[i].find("the");
if (found != string::npos)
++counter;
}
// Prints how many it found
cout << counter << endl;
}
Hope this helps and wish you the best of luck, let us know if you have any questions.
Also MiiNiPaa's approach is much better since in his example you don't need to store anything you just go through the file word by word and examine each word for "the". I just figured storing the words might show how this works a little better.