Source of cstr1.cpp


  1: // Filename: CSTR1.CPP
  2: // Purpose:  Illustrates C-style strings: declaration, initialization,
  3: //           copying, concatenation, computing length, output with cout.

  5: #include <iostream>
  6: #include <cstring>
  7: using namespace std;

  9: #include "PAUSE.H"

 11: int main()
 12: {
 13:     cout << endl;
 14:     cout << "This program illustrates declaration, "
 15:          << "initialization, copying, concatenation, "   << endl
 16:          << "and output with cout, of C-strings. "
 17:          << "Study the source code while running it. "   << endl;
 18:     cout << endl;
 19:     Pause(0);

 21:     // You can initialize a C-string variable in its declaration:
 22:     char s1[8] = "Hello, "; // OK
 23:     char s2[] = "world!";   // OK, and also avoids character counting!

 25:     // But you can't assign to a C-string variable after declaring it:
 26:     // char s3[21];
 27:     // s3 = "Hello, world!";  // Not OK; gives a compile-time error

 29:     // So, you have to "copy", *not* assign, one string to another:
 30:     char s3[21];
 31:     strcpy(s3, s1);  // Note that the copying is *from* s1 *to* s3.

 33:     // This is how we append string s2 to the end of string s3:
 34:     strcat(s3, s2);

 36:     // Now we print out the three strings and their lengths:
 37:     cout << "Length of \"" << s1 << "\" is " << strlen(s1) << "." << endl;
 38:     cout << "Length of \"" << s2 << "\" is " << strlen(s2) << "." << endl;
 39:     cout << "Length of \"" << s3 << "\" is " << strlen(s3) << "." << endl;
 40:     Pause(0);

 42:     // We can also use "typedef" to define a "C-string type", as in
 43:     typedef char String20[21];  // The "extra" location is for the '\0'.

 45:     // Note that strcpy may also be treated as a value-returning
 46:     // function that actually returns the string result of the copy.
 47:     String20 s4, s5;
 48:     cout << strcpy(s4, "How are you?") << "<<" << endl; // Here we are
 49:     cout << strcpy(s5, "Fine!")        << "<<" << endl; // displaying the
 50:     Pause(0);                          // return-value of function strcpy.

 52:     // Note that copying a shorter string to a longer string
 53:     // "does the right thing" and puts the '\0' in the right place.
 54:     cout << s4 << "<<" << endl;
 55:     strcpy(s4, s5);
 56:     cout << s4 << "<<" << endl;
 57:     Pause(0);

 59:     return 0;
 60: }