I have a file of a bunch of words and want to extract the ones that contain a 'q' or 'Q'. I have a function called isQWord that scans a string for these letters and, if it does contain these letters, puts the word into a vector called qwords. The function also does a few other things, but I've omitted these parts because they don't pertain to the issue. Then, in my main function, I use isQWord to read all the strings from my file. Here is my code:
bool isQWord(string str); // return true if str contains a 'q' or 'Q'
ifstream inFile;
vector<string> qwords;
int main() {
string str;
inFile.open("DictionaryLarge.txt");
while(!inFile.eof()) { // go through contents of DictionaryLarge.txt
inFile >> str;
isQWord(str); // call isQWord function on file contents
}
inFile.close();
outFile.close();
}
bool isQWord(string str) {
/* This function does three things:
1. scans a string for 'q' or 'Q'
2. appends q-words to the qwords vector
3. finds the largest q-word and stores all q-words before this word to an output file
*/
for(int x=0; x < str.size(); x++) { // read string
if(str.at(x) == 'q' || str.at(x) == 'Q') { // append to qwords vector for q-words
qwords.push_back(str);
return true;
}
else if(str.size()==0) { // return false for blanks
return false;
}
else { // return false for non q-words
return false;
}
}
}
However, the for loop in isQWord is "stuck", so to speak, at my starting value of x = 0 and only returning words that begin with 'q' or 'Q' only. That is, it's reading something like if(str.at(0) == 'q' || str.at(0) == 'Q')
and completely bypassing the for loop.
I've also instead tried a while loop like this:
int i=0;
while(str.size() != 0) {
if(str.at(i) == 'q' || str.at(i) == 'Q') {
qwords.push_back(str);
break;
}
i++;
}
but this throws an error in my main function when I try to call isQWord on my file contents. I'm hoping to stick with the for loop because I think this is closer to working.
Also, I realize there are certain library functions I could be using that would make this easier, but this is a homework assignment and I'm only allowed to use .size() and .at() to search for 'q's and 'Q's.
Thank you for any guidance.