I have a program that reads txt from a file and counts how many words there are. I need to modify it to count how how many occurences of a certain word there is, in Java I'd do something like:
for(string s:x){
//do something
}
How can I do something like this in C++? While the program is reading the file, I need it to add 1 everytime the next word is "SPECIAL".
I'm a bit stuck if I'm honest, don't really know what I should be reading.
To count how many occurences of S are in X, the C++ solution is to call std::count(X.begin(), X.end(), S)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::string word = "SPECIAL";
std::ifstream file("test.txt");
std::istream_iterator<std::string> beg(file), end;
unsignedint cnt = count(beg, end, word);
std::cout << "the word '" << word << "' found " << cnt << " times\n";
}
Although you can certainly do it the way you describe
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::string word = "SPECIAL";
std::ifstream file("test.txt");
unsignedint cnt = 0;
for(std::string s; file >> s; ) // While the program is reading the file
if(s == word) // everytime the next word is "SPECIAL".
++cnt; // add 1
std::cout << "the word '" << word << "' found " << cnt << " times\n";
}