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

C++ Primer Plus Chapter 4 Exercise 4

c plus plusWith some minor adjustments, we can use the C++ string class to accomplish our goal.  We will use the C++ member function ‘append’ from the string class. My solution if fairly clean and simple. Here is the source:

4. Write a program that asks the user to enter his or her first name and then last name, and
that then constructs, stores, and displays a third string consisting of the user’s last name
174 C++ PRIMER PLUS, FIFTH EDITION
followed by a comma, a space, and first name. Use string objects and methods from the
string header file. A sample run could look like this:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: Fleming, Flip

#include <iostream>
#include <string>

using namespace std;

int main()
{
string firstName;
string lastName;
string str;

// Gather input, could use cin.getline here.
cout << "Enter your first name: ";
cin >> firstName;
cin.ignore();
cout << "Enter your last name: ";
cin >> lastName;

// Using C++ string member functions
str.append(lastName);
str.append(" , ");
str.append(firstName);

cout << "Here's the information in a single string: " << str << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 2

c plus plusExercise 2 requires us to make some minor adjustments to allow for the C++ string class.  By simply deleting any reference to an array and adjusting our getline statement, we have listing 4-4 working for the C++ string class:

2. Rewrite Listing 4.4, using the C++ string class instead of char arrays.

#include <iostream>
#include <string>

using namespace std;

int main()
 {
 string name;
 string dessert;

cout << "Enter your name: ";
 getline(cin, name);

cout << "Enter your favorite dessert: ";
 getline(cin, dessert);

cout << "I have some delicious " << dessert
 << " for you, " << name << endl;

return 0;
 }