C++ Primer Plus Chapter 5 Exercise 8

c plus plusWith some slight modifications we can breeze through exercise 8. The instructions require us to use the natural <string> header for C++ string class objects. The key point here is that using string is simply just easier. Why you ask? Because we can now use ‘!=’  and other comparative operators to make our comparisons.  See my solution below:

8. Write a program that matches the description of the program in Programming Exercise 7, but use a string class object instead of an array. Include the string header file and use a relational operator to make the comparison test.

#include <iostream>
#include <string>

using namespace std;

int main()
{
string input;
int words = 0;
string compare= "done";

cout << "Enter words (to stop, type the word done):" << endl;
cin >> input;

while(input != compare)
{
cin >> input;
words++;
};

cout << "You entered a total of " << words << " words " << endl;

cin.get();
return 0;
}
Advertisements

4 thoughts on “C++ Primer Plus Chapter 5 Exercise 8

  1. This seems to meet the criteria for exercise 9, chapter 5. Exercise 8 requires the use of the cstring header file and strcmp() function.

    “//exercise8.cpp — chapter 5.
    //Michael R.
    #include
    #include
    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." <> words;
    }

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

    return 0;
    }
    "

    The previous was my solution. If anyone knows how I can get rid of the second to last line code "(wcount -1)", please inform me.

    • I think you meant ch5e7 and ch5e8. Exercise 9 is totally different. I can’t tell what was left out, but we do need to be using C++ string class this time and the word done to stop reading. What I was getting at with the solution for exercise 8 is that we can now just use comparative operators on the strings.

  2. Whoah, the vital parts of my code didn’t paste well into my last reply. Sorry about that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s