Lab 6 - String Handling

The purpose of this laboratory assignment is to learn more about string handling, including allocation and copying.

The cstring library provides several predefined functions to manipulate C-style strings. Likewise, the C++ string class provides another mechanism to store and manipulate strings. The underlaying feature of both is to have a character array where the last character in the string is the null character, '\0', which is used as a sentinel value to mark the end of the string.

For this lab, we are going to pretend that these functions do not exist. We are going to write a function called char *getAndCopy(char *, int) which will recreate both cin.getline() and strncpy(). This function will read characters from the keyboard, up until the given limit or the newline character. It will then allocate a second character array and copy all the characters it just read into the second array. It will then return the second array.

It is very critical that you set the null character after reading the characters from the keyboard. If the null character is not set, any attempt to output or manipulate the string will keep going character-by-character in memory until it randomly comes across a null character.

The pseudocode for this function is as follows:

Function getAndCopy(char *str, int max):
  declare a temporary single character called c
  declare a temporary character pointer called tmp
  declare an integer called count and initialize to 0

  cin.get(c)
  while c is not '\n' and count is less than max-1
    copy c into str at index count
    increment count
    cin.get(c)
  end-while
  set index count in str to the null character

  use new command to allocate count+1 characters to tmp
  if allocation fails
    return NULL
  else
    for each character in str (index 0 to count-1)
      copy str's character over to tmp
    end-for
    set the null character at the end of tmp
    return tmp
  end-if
Note that you could also create a function called char *getAndReverse(char *, int) by changing the final for() loop to count down from count-1 to 0 for str's index number and to count up for tmp's index number.

Use the following main() function:

int main()
{
  char line[121];
  char *copy = NULL;

  copy = getAndCopy(line, 120);

  cout << "Pointer information.\n";
  cout << "Address of line: " << &line << endl;
  cout << "Address of copy: " << &copy << endl;
  cout << "Base address of line pointed to by copy: " << &(copy[0]) << endl;

  cout << "\nContents of the strings:\n";
  cout << "Line: " << line << endl;

  if(copy == NULL)
  {
    cout << "Copy failed!\n";
  }
  else
  {
    cout << "Copy: " << copy << endl;
    delete [] copy;  // Deallocate the string
  }

  return 0;
}
Email me the complete lab6.cpp with the above main() function and your coded getAndCopy function.