Eric Teunis de Boone
969ee37aa8
We do not know how long the words will be (except not longer than a line) so a std::string more suitable for this. Plus, we can now use instead of checking for a character ourselves.
55 lines
975 B
C++
55 lines
975 B
C++
#include <fstream>
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <sstream>
|
|
|
|
int main( int argc, char* argv[] ) {
|
|
|
|
|
|
if ( argc != 2) {
|
|
std::cout << "usage: " << argv[0] << " FILENAME" << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
std::ifstream fh(argv[1]);
|
|
|
|
if ( !fh ) {
|
|
std::cout << "Error opening File '" << argv[1] << "'" << std::endl;
|
|
return 2;
|
|
}
|
|
|
|
unsigned int linecount = 0;
|
|
unsigned int charcount = 0;
|
|
unsigned int wordcount = 0;
|
|
const int bufsize = 100;
|
|
char buf[bufsize];
|
|
|
|
// if EOF, fh returns false
|
|
while( fh ) {
|
|
fh.getline(buf, bufsize);
|
|
|
|
charcount += strlen(buf)+1; // Newlines are not counted normally, but they are a character
|
|
linecount++;
|
|
|
|
std::istringstream line(buf);
|
|
while( line ) {
|
|
std::string linebuf;
|
|
|
|
line >> linebuf;
|
|
|
|
if ( ! linebuf.empty() ) {
|
|
wordcount++ ;
|
|
}
|
|
|
|
|
|
if ( line.eof() )
|
|
{
|
|
break ;
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
|
|
std::cout << " " << linecount-1 << " " << wordcount << " " << charcount-1 << " " << argv[1] << std::endl;
|
|
}
|