Sample Program: C Style Strings

main.C

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

int main()
{
  char line[80];
  char hi[] = "Hi Mom!";
  char hidad[]= "Hi Dad!";
  char word[15];
  char another[15];
  char first[21];
  char sec[21];
  char third[31];

  //  read in some words and print them
  cout << "Enter two words: ";
  cin >> word >> another;
  cout << "The words you entered were: \n"
       << "   " << word << endl
       << "   " << another << endl;

  //  copy a string and print the copy
  strcpy(first,hi);
  cout << "hi contains: " << hi << endl;
  cout << "first contains: " << first << endl;

  //  read in a string and concat it if there is room
  cout << "Enter a string (max 20 chars): ";
  cin.getline(sec,21);
  if (strlen(sec) + strlen(first) < 30)
    {
      strcpy(third,first);
      strcat(third,sec);
      cout << "The concatenated string is: " << third << endl;
    }
  else
    cout << "Not enough room to concatenate\n";

  //  compare some strings
  if (strcmp(first,hi) == 0)
    cout << "hi and first are the same\n";
  if (strcmp(hi,hidad) < 0)
    cout << hi << " is less than " << hidad << endl;
  else
    cout << hidad << " is less than " << hi << endl;

}

Output:

Enter two words: autumn   winter
The words you entered were:
   autumn
   winter
hi contains: Hi Mom!
first contains: Hi Mom!
Enter a string (max 20 chars): all you need
The concatenated string is: Hi Mom!all you need
hi and first are the same
Hi Dad! is less than Hi Mom!



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

© Copyright Emmi Schatz 2004