Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 7. Strings: Analyzing the Text > Example 7.1. Building Strings

Example 7.1. Building Strings

Let’s start with a simple string operation: building a string out of smaller strings. The following program gets a couple of strings from the user (by calling the getline function, described later), builds a larger string, and then prints the results:

buildstr.cpp

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str[600];
    char name[100];
    char addr[200];
    char work[200];

    // Get three strings from the user.

    cout << "Enter name and press ENTER: ";
    cin.getline(name, 99);
    cout << "Enter address and press ENTER: ";
    cin.getline(addr, 199);
    cout << "Enter workplace and press ENTER: ",
    cin.getline(work, 199);

    // Build the output string, and then print it.
    strcpy(str, "\nMy name is ");
    strcat(str, name);
    strcat(str, ", I live at ");
    strcat(str, addr);
    strcat(str, ",\nand I work at ");
    strcat(str, work);
    strcat(str, ".");

    cout << str << endl;

    system("PAUSE");
    return 0;
}

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial