Strings

  1. ANSI C++ can handle sequences of characters called strings.

  2. Strings behave like (but are actually not) a build-in data type such as int or double. They are actually objects of the C++ standard string class (more on that a month or so from now).

  3. The syntax for declaring an object of type string is:

    string stringName;

  4. You must include the header file <string> in order to use the strings:

    # include <string>

  5. The string class overloads the = operator to copy one string of any length into another. (More about overloading operators in CS1124.) For example:

    stringName = "The 3 rings associated with marriage are: engagement ring, wedding ring, and suffering."

  6. cin and cout, together with the operators >> and <<, are overloaded to perform input and output of strings. It is important to note that cin >> ignores leading whitespaces (a space, a tab or a newline character) and reads up to the next whitespace (but does not consume that whitespace, i.e. it is left in the input buffer stream). Reading strings this way actually reads words (a sequence of non-whitespace characters) and not lines.

  7. To illustrate the usage of some of the features about the string class, consider the following code:

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

    int main( )
    {
    string compoundWord, word1, word2;
    cout << "Enter two separate words: ";
    cin >> word1 >> word2;
    compoundWord = word1 + word2;
    cout << "These words joined together form the string: " << compoundWord << endl;

    return 0;
    }

    Two words entered from the keyboard are stored separately in strings word1 and word2. They are then concatenated (joined together) by the overloaded operator "+", and assigned to the string compoundWord. The result is then output to the screen.