Real quick question regarding strcmp() function

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//exercise8.cpp -- chapter 5.
//Michael R. Benecke
#include <iostream>
#include <cstring>
int main()
{
    using namespace std;
    char words[200];
    int wcount = 0;

    cout << "Enter words, separated by spaces. Use done to stop counting words.  Press enter to complete counting procedure." << endl;
    for (wcount = 0; strcmp("done", words); ++wcount)
    {
        cin >> words;
    }

    cout << "You entered a total of " << (wcount -1) << " words.";

    return 0;
}
Last edited on
closed account (NyqLy60M)
I don't recommend macros, but clearly you're after aesthetics so you could try this:

1
2
3
4
5
#define DONE strcmp("done", words) // a not-so-good idea

..

for (wcount = 0; DONE; DONE ? ++wcount : wcount){ ... }
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. :-)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//exercise8.cpp -- chapter 5.
//Michael R. Benecke

#include <iostream>
#include <cstring>
#include <iomanip>

int main()
{
    const int 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;
}
1
2
    while ( (cin >> words) && strcmp("done", words) )
        ++wcount;
Last edited on
Topic archived. No new replies allowed.