C++ functions needed to sort strings

While there are many ways to sort the actual list, there are a few string functions you will need regardless, and they can be demonstrated by sorting two strings into alphabetical order.

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

void WordSwap(char [], char[]);

void main()
{
  char wordA[20], wordB[20];  // our two words
  cout << "Give two words, separated by a space \n";
  cin >> wordA >> wordB;
  
  cout << "Original order:  " << wordA << '\t' << wordB << endl;

  // strcmp returns a value < 0 if wordA < wordB lexicographically,
  //                        = 0 if wordA == wordB lexicographically,
  //                        > 0 if wordA > wordB lexicographically
  if (strcmp(wordA, wordB) > 0)
    WordSwap(wordA, wordB);

  cout << "Final order:  " << wordA << '\t' << wordB << endl;
}

void WordSwap(char word1[], char word2[])
{
  char temp[20]; // temporary holder word
  
  strncpy(temp, word1, 19);
  temp[19]='\0';
  strncpy(word1, word2, 19);
  word1[19] = '\0';
  strncpy(word2, temp, 19);
  word2[19] = '\0';
}

At this point, you can add your own sort code to sort the words. (Ahem, that's a cue for class discussion!)


Next: sorting by length? and alphabetically? And how alphabetical is lexicographic really?