C++ Primer Plus Chapter 4 Exercise 3

c plus plusExercise 3 of chapter 4 wants us to do some specific things with cstrings. We can use strcpy and strcat member functions from the cstring class to make our third string adhere to the requirements.  Here is my solution :

3. 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
followed by a comma, a space, and first name. Use char arrays and functions from the
cstring 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 <cstring>
#include <string>

using namespace std;

int main()
{
char firstName[20];
char lastName[20];
char str[50];

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

// C string member functions
strcpy_s(str, lastName);
strcat_s(str, " , ");
strcat_s(str, firstName);

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

cin.get();
return 0;
}
Advertisements

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