Basically you need your program to do two things, count the number of lines and count the number of words in a file. Luckily there is a getline function available. Also, there is a version that takes a filestream and a string. Something like this:

Code:

std::string aLine;
std::ifstream myFile( filename.c_str() );

// To get one line from the file
getline( myFile, aLine )

In the above snippet, aLine will now contain the first line of the file. Now, you need to figure out how many words are in that line. You can use strtok, but I am quite fond of stringstreams. With them I can do something like:

A stringstream provides a nice interface from converting from a string to a stream and back to a string again. What I did above was convert the line into a stream. This lets me have control over parsing, counting, etc.

As Paul has mentioned, learning to use the debugger is vital. Also, Google is your friend. Be sure to examine the examples. Try not to panic. You will save yourself time by spending a little extra up front examining the examples and understanding them. Afterward, if you have a question about an example, then by all means, you can ask.

Finally, with the two things I mentioned here (and, pretty much using just the two things), I would be able to write a program to do your assignment.

I hope this helps you.

January 30th, 2012, 11:59 AM

jedipenguin

Re: Need to print out number of words and lines in a file

I've tried that and now I'm getting a segmentation fault. (Right now I'm telling it to use the filename as a command line argument rather than read in to see if it just can't read files.

int total = 0;
for (int i = 0; i < v.size(); i++) {
total = total + v[i];
}

cout << "Word count: " << total;
cout << "\n";
return 0;
}

January 30th, 2012, 01:22 PM

Lindley

Re: Need to print out number of words and lines in a file

Quote:

Originally Posted by jedipenguin

I'm unsure of whether I should be using the fstream getline or the global getline.

The fstream's getline (which is actually inherited from istream) takes a C-style string (char array) as its input destination. This brings along with it all the perils of C-style strings, so I do not recommend it.

The global getline is for use with std::strings, which are much safer and easier to use.