if (!inFile) // How do I use assert function here???
First of all, assert is a macro, not a function (an
important distinction in this case).
Second, assert isn't really suitable for this situation
anyway. It's basically intended to verifying program
logic -- i.e. if its condition is false, it indicates a
problem in your program, rather than data that's supplied
to the program. This is looking at the input data, so an
'if' is a perfectly reasonable way to handle it.
For real use, an interactive program like this that
requires the user to type in file names as it runs is
rarely as useful as a program that accepts file names on
the command line so the user can specify all of them up-
front. Along with that, I'd move the counting into a
separate function:
int count(char const *filename) {
int words = 0;
std::string word;
std::ifstream infile(filename);
if (!infile)
return -1;
while (infile >> word)
++words;
return words;
}
int main(int argc, char **argv) {
for (int i=1; i<argc; i++) {
int words = count(argv
);
std::cout << argv << ": ";
if (words < 0)
std::cout << "Unable to open file!\n";
else
std::cout << count(argv) << "\n";
}
return 0;
}
One other possibility would be to use std::distance
instead of an explicit loop to count the words in the
file:
int count(char const *filename) {
std::ifstream infile(filename);
if (!infile)
return -1;
return std::distance(
std::istream_iterator<std::string>(infile),
std::istream_iterator<std::string>());
}
Side note: A typical UNIX shell will expand wildcards and
such, so this will automatically support things like "wc
*.txt". Most shells in Windows don't do that, but most
compilers include code to do it that you can link into
your program if you want it (its name varies from one
compiler to the next though -- e.g. Microsoft calls it
setargv.obj, Borland calls it wildargs.obj, and so on).
--
Later,
Jerry.
The universe is a figment of its own imagination.