Question

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.

Was it helpful?

Solution

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++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top