next up previous
Next: About this document ... Up: A Second C++ Program: Previous: Explanation of the Program

The string class

The standard library that comes with modern C++ compilers simplifies the treatment of character strings by keeping track of their length and allowing other manipulation. We discuss classes later in this course, but for now we can treat it as just another variable type.

Here is the same code with the string class for the variable name.

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

int main()
  int age;
  string name;

  cout << "enter name and age: \n";
  cin >> name >> age;
  cout << "Your name is " << name
       << " and age is " << age << "\n";

Notice that we need to include the <string> header and we do not specify the length of the string when we declare it. Also notice that cin and cout know how to process the string type in a natural way.

Carleton DeTar 2008-09-03