I am looking to find the number of words that start with d, D, or any other character within a file. Currently I am having trouble counting each instance of a new word. For example, if there are 5 Davids and 3 Dogs within the file, I would want to count each of them individually.
I would prefer something that would not require massive change. Any help is appreciated.
#include<iostream>
#include<fstream> //needed for file opening and closing/manipulation within files
#include<vector> //needed for vectors to store the words from the file
#include<algorithm> //needed for sort algorithm later
using namespace std;
int main(){
string inputName, num, words;
cout<<"Enter a valid filename: "; //Prompting user for a file name in the directory of this program exe
cin>>inputName;
ifstream file(inputName); //Creating a ifstream File which will open the file to the program
vector<string> dWords; //Creating 2 vectors, 1 for anything that starts with 'd'/'D' and 2 for anything else
vector<string> otherWords;
while(!file.eof()){ //While loop that runs until the file is eof or end of file.
getline(file, words);
while(file>>words){ //Reading each line and extracting into the words variable
if(words[0]=='d'||words[0]=='D'){ //if statement that checks if the first letter in each word starts with a 'd' or 'D'
dWords.push_back(words); //if true then the word gets added to the vector with the push_back
}
else if(words[0]=='"'){ //Checking for a niche case of when a word starts with a "
if(words[1]=='d'||words[0]=='D'){//If true then the same if statement will happen to check for 'd' or 'D'
dWords.push_back(words);
}
}
else{ //This case is for everything not mentioned already
otherWords.push_back(words); //This is added to a different vector than the dWords
}
}
}
dWords.erase(unique(dWords.begin(), dWords.end()));
otherWords.erase(unique(otherWords.begin(), otherWords.end()));
sort(dWords.begin(), dWords.end()); //Using the C++ native sorting method that works with vectors to sort alphabetically
sort(otherWords.begin(), otherWords.end());
cout<<"All words starting with D or d in the file: "<<endl; //printing out the words that start with 'd' or 'D' alphabetically
for(int a=0; a<=dWords.size(); a++){
cout<<dWords[a]<<endl;
}
cout<<endl;
cout<<"All words not starting with D or d in the file: "<<endl; //printing out every other word/character left
for(int b=0; b<=otherWords.size(); b++){
cout<<otherWords[b]<<endl;
}
file.close(); //closing file after everything is done in program
}