I wrote the following code to count words until done is entered. But, my counter seems less than efficient. In line 17, I had to use (wcount - 1) in order to get the correct number of words. "Done", the exit word, should not be counted as a word. I have to use strcmp(). Is there any way to re-write the code so that I don't need to have the (wcount - 1) bit?
I'm not sure it's worth the hassle. It's not really inefficient to subtract one from a value. In fact, it can be quite common throughout programming (you might see a lot of size-1 in loops).
Because of the way you're counting your words I can't see any obvious elegant solution for the count. However, seeing as it looks like you're working through a book I wouldn't hang up on it too much. You'll probably be getting rid of C-strings in the future. :-)
//exercise8.cpp -- chapter 5.
//Michael R. Benecke
#include <iostream>
#include <cstring>
#include <iomanip>
int main()
{
constint SZ = 200 ;
char words[SZ];
int wcount = 0;
std::cout << "Enter words, separated by spaces. Use done to stop counting words.\n"
<< "Press enter to complete counting procedure.\n" ;
// std::setw http://en.cppreference.com/w/cpp/io/manip/setw
// do not allow more than SZ-1 letters per word. (we do not have
// the space to store more than SZ-1 characters plus the terminating null character.)
while( std::cin >> std::setw(SZ) >> words && strcmp("done", words) != 0 ) ++wcount ;
std::cout << "You entered a total of " << wcount << " words.";
// return 0;
}