Counting specific string in a TXT file

I'm needing to search through a text file and count the occurences of a specific string within the file. For example, the file contains many occurences of "V00289441" and such. I need to count how many times "V00" appears. I have found and modified code that will allow me to type a word in and it will tell me how many times it shows up, but it is case sensitive and has to match exactly. For example, if I simple type "V00" it will count 0, but if I type the entire string "V00289441", it will count to 1. I need to it count every occurence of "V00". So if I do a search for how many times the word "Date" appears, it will only count it if it is "Date" exactly. It won't count if it finds "Date:" or "date" or "DATE". Here is the code I used to count:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

string inputword();


int main()
{
ifstream infile("rt.txt");
int cnt = count( istream_iterator<string>(infile), istream_iterator<string>(), inputword());
cout << cnt << endl;
}

string inputword()
{
cout << "Enter a word to be counted in a file: ";
return *istream_iterator<string>(cin);
}
I think your problem is here:

int cnt = count( istream_iterator<string>(infile), istream_iterator<string>(), inputword());

count needs to know the end of the string or the length to parse, and it doesn't seem that you are providing that.
Yes, I agree. I am sure I need to use a different function. This one works for what it was meant to - to count an input word - but I need something different that will let me count portions of a string. Think of it like "Search and Replace" in MS Word. If I tell it to replace "car" with "hat", it will find "car", "cart", "scar", "vicar" and make them all "hat", "chat", "shat", and "vihat". I need mine to work like this, except do a count for each time it finds the string, in this case "V00".
How about count_if() ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

string inputword();

class F {
private:
string m;
public:
F() : m(inputword()) { }
	
bool operator()(const string& s) const
{
return m.npos != s.find(m);
}
};

int main()
{
ifstream infile("rt.txt");
int cnt = count_if( istream_iterator<string>(infile), istream_iterator<string>(), F() );
	
cout << cnt << endl;

return 0;
}

string inputword()
{
cout << "Enter a word to be counted in a file: ";
return *istream_iterator<string>(cin);
}
Last edited on
Topic archived. No new replies allowed.