I'm in the early stages of C++. Right now, I'm trying to write a program that will read a file and print the number of times a word appears in the file. The program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
usingnamespace std;
int main(){
vector<string> words;
ifstream in("test.txt");
string word;
int num = 0;
while(in >> word)
words.push_back(word);
for(unsignedint i = 0; i < words.size(); i++)
if (word == "test")
++num;
cout << "There are " << num << " occurrences of the word \"test\"\n";
}
Right now, test.txt says "these are words test". However, the output of the program says there are four occurrences of the word. It seems that it gives 0 if test doesn't appear in the file (as it should), but gives the number of all words in the file if test appears even once. What am I doing wrong?
for(unsignedint i = 0; i < words.size(); i++)
if (word == "test")
++num;
what's missing is indexed access to the vector, the current word is always the last that was added, which is stored in the string "word" by cin and it's counted by your code 4 times according to words.size().