Skip to main content

Exercise 6.2: sort-strings-1.0.cpp

//sort_strings-1.0.cpp
//Solution to Exercise 6.2

//Reads in words from the console into a
//vector of string variables, then outputs the
//words in dictionary order to the console.

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

typedef vector<string> strvec;

int main()
{
  strvec sv; //empty vector of strings to store words
  string sorted; //empty string of sorted words
  //get words from input
  cout << "Enter the words for sorting, end with ' ! ':" 
       << endl;
  while (true)
    {
      string word;
      cin >> word;
      if (word == "!") break;
      sv.push_back(word);
    }

  //sort words - there are many ways of doing this
  for (int w = 0; w < sv.size(); w++)
    {//loop through each word
      for (int c = w+1; c < sv.size(); c++)
	{//compare with each other word in turn
	  if (sv[c] < sv[w])
	    {//if then other word is earlier in order
	     //then swop positions and continue
	      string temp = sv[w];
	      sv[w] = sv[c];
	      sv[c] = temp;
	    }
	}
    }
     
  //concatenate into one string
  for (int w = 0; w < sv.size(); w++)
    {
      sorted = sorted + sv[w] + "\n";
    }
      
  //output sorted string to console
  cout << endl << sorted;
  
  system("PAUSE");
  return(0);
}