Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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:
|
Code View:
Scroll
/
Show All #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;
}
|