Hi,
I've just done an exercise from a book that counts the number of occurences of a word in an input. I have done this, and it works. However, i'm not sure if this is a good way to do it? I was a little confused at the start regarding the loop/vector off by one idea and tried to work around that. I am aware of strcmp, however I have not reached that yet in the book and as such, tried to do this without using that function. Any comments would be welcome.
Code:void CheckWords(const Vector<string>& wds) { int counter = 1; for(int i = 0; i<wds.size()-1; ++i){ //check if word equal to next word, if so increment counter if(wds[i] == wds[i+1]) ++counter; else{//if not equal, print the word and the number of occurences cout << wds[i] << " Counter: " << counter << endl; counter = 1; } //check if word is penultimate and if matches last word or not. if(i == wds.size()-2){ if(wds[i] == wds[i+1]){ cout << wds[i] << "counter: " << counter << endl; counter = 1; } if(wds[i] != wds[i+1]){ cout << wds[i+1] << "counter 1" << endl; counter = 1; } } } }



LinkBack URL
About LinkBacks



