简体   繁体   中英

How do I count the number of occurrences of a specific word in a text file

I'm stumped by an assignment I'm working on and don't even know where to really begin, i think what I have may be completely useless.

I'm trying to read a text file that contains 8 lines of text, each with the word "line" somewhere in the line. I need to count the total number of times that the word "line" appears in the file.

Code I have so far

ifstream file("output.txt");    
int wcount = 0;
string token;
string word(line);
while (file>>token)
    if (word == token)
    wcount++;

cout << wcount << endl;

I've been looking at this for hours and searching for every possible solution and coming up with nothing. Please help.

Change this line:

string word(line);

to

string word("line");

Update

To check whether the file was opened successfully...

ifstream file("output.txt");
if ( !file )
{
   // Deal with error.
}

// Read the contents of the file.

To check whether the words are being read correctly...

while (file>>token)
{
    std::cout << "Read the token: `" << token << "'" << std::endl;
    if (word == token)
       wcount++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM