Sample Program Using String Objects


#include <iostream.h>
#include <string>

int main()
{
   string line;
   string word;
   string exact("Hi Mom!");
   string another(exact);

//  read one word using >>
//  >> skips leading whitespace, reads one word, and stops when
//  it sees trailing whitespace
   cout << "Enter a word: ";
   cin >> word;
   cout << "The word was: " << word << endl;

//  the trailing whitespace ('\n') is not read by >>, so use cin.get
//  to read it in
   char junk = cin.get();

//  getline reads all chars up to '\n'
//  '\n' is read in but not added to the string
   cout << "Enter a phrase: ";
   getline(cin,line);
   cout << "The phrase was: " << line << endl;

//  show result of initialization
   cout << "exact contains: " << exact << endl;
   cout << "another contains: " << another << endl;

   string dup;
   dup = word;

//  show result of assignment
   cout << "dup contains: " << dup << endl;

//  show result of comparison
   if (word == exact)
      cout << "word and exact are the same\n";
   else
      cout << "word and exact are not the same\n";
}

Output:

Enter a word:    door
The word was: door
Enter a phrase: blowing away
The phrase was: blowing away
exact contains: Hi Mom!
another contains: Hi Mom!
dup contains: door
word and exact are not the same


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002