January 29th, 2012, 11:39 PM
Re: Need to print out number of words and lines in a file
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:
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:
std::ifstream myFile( filename.c_str() );
// To get one line from the file
getline( myFile, aLine )
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.
std::stringstream tempStream( aLine );
while( tempStream >> temp )
// Do something
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.
Click Here to Expand Forum to Full Width
This is a Codeguru.com survey!