How to read a specific word from a file?

How would one go about doing this? I am very fond with Windows I/O, but not so much with this subject. I am decent with fstream, probably not as skilled at it as I should be, but I assume <fstream> would be a better choice, since it isn't locked to Windows.

Anyway, say I have a .txt file like this:

Bill is a cow.
Bill likes meat.
Bob is a pig.
Bob and Bill are friends.


And I want to count the number of times "Bill" is written. How would I do that?
istream's >> operator extracts things one word at a time (seperated by whitespace). So just keep extracting words with >> until you reach the end of the file. And count the number of times the word you extracted was "Bill"

Note that if punctuation is an issue, you'll have to manually remove the punctuation from the extracted word. IE: "Bill." would not match "Bill" because of the period.
Use a do while loop to iterate through the file and use the std::string.compare() or std::string.find() member functions to evaluate the portion of the file you read in. If you find one matching "Bill" then increment some counter variable. So something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string Bill = "Bill";
std::string Input;
std::ifstream iFile("Your_File.txt", std::ios_base::in);
unsigned Counter = 0;

do
{
     iFile >> Input;
     
     if(Bill.compare(Input) == 0)
    {
             Counter++;
     }
}while(!iFile.eof());


Or something similar.
Last edited on
Wow that makes a lot of sense. I haven't tried it yet, since I am exhausted and about to pass out on my desk and don't feel like opening up VSC++, I will probably test that code in the morning or after school tomorrow. Thanks for the answers, guys! I be here tomorrow!

Laziness gets us all....
Last edited on
Okay, just tried the code.
How would I print just "Bill" in the program?

As you can tell I haven't used fstream for a couple months, I have been using (like I said) windows I/O for whatever reason.
Last edited on
Using Computergeek01 code:

1
2
3
#include <iostream>
...
std::cout << Bill << ": " << Counter << std::endl;
Topic archived. No new replies allowed.