Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 10: The String Class

The String Class

String Class

  • Defined in the std namespace in the “string” library, so you need to
    #include <string>
  • Easier to use! No size constraints! Dynamic allocation of needed memory!
  • Length of string is returned by member function
  • Square braces work for strings, but no range checking is done (as with any array indexing)
  • The member function

    also references a character of the string, but it does range checking. Program will abort and dump core if reference out of range.

  • The following operators all have their intuitive meanings for string objects:
     =    ==    !=    +    +=
  • Sec. 9.7 has a good table on many ways to use the string class.
  • The getline function is a bit different with string objects. It is not a member function of cin like the getline that works with cstrings. It has the following two overloaded prototypes:
    string& getline(istream& ins, string& strVar, char delimiter);
    string& getline(istream& ins, string& strVar); // uses '\n' as delimiter

    So to input a line from the keyboard and store it in the string object “class_title”:

        string class_title;
        cout << "Enter name of class";
        getline(cin, class_title);
        // An entire line of exact user input will be stored
        // in class_title. e.g. "Programming Fundamentals I"
  • Example program: Name program using string objects
  • In-class exercise: Change the Password program to use string objects instead of cstrings.
  • Solution to above in-class exercise