Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Sorting Arrays of Strings

Posted on 2003-03-02
9
Medium Priority
?
288 Views
Last Modified: 2013-12-14
I am currently trying to build a simple program that will allow me to build a small database of cars and then query the database by certain criteria.  The information for the database is placed into the program via an input text file ("car.txt").  I have used the typedef command to build arrays of strings (rather than arrays of characters) to use in the program.  There are actually three main arrays that I have built:  one containing strings of the the cars make and model, one containing the work order number which is an array of integer and one containing strings of the mechanics last names.  I need to sort the arrays by work order number and so I have set up a function to sort all three arrays.  I can sort the workorder array without problem and obviously, the corresponding subscript numbers in the other two string arrays should be sorted exactly the same as the subscript numbers in the workorder array in order to keep the records of all three in sync.  However, I haven't been able to do that.    Here is my source code for the problem that I have so far.  I appreciate any help that anyone can give me!

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

typedef char nameString[20];
void sort(nameString a[], int b[], nameString c[], int d);

int main()
{
      int workorder[50];                              //***Array of work order numbers***
      
      typedef char nameString[20];            //***Array of 20 strings containing car
                                                            //       first names***
      nameString mechanic[20];                  //***Array of last names of mechanics***
      nameString firstName[50];                  //***Array that contains 50 characters that
                                                            //   make up car first names***
      nameString lastName[50];                  //***Array that contains 50 characters that
                                                            //   make up car last names***
      nameString car[50];                              //***Array that contains the combined first
                                                            //   and last names
      int cnt=0;
      int i=0;
      int count;
      ifstream inFile;

      inFile.open("car.txt");

      if (!inFile)
            cout << "This file did not open" << endl;
      else cout << "This program did open" << endl;

      inFile >> count;
            cout << count << endl;

      for  (i=0; i < count; i++)
      {
            inFile >> firstName[i] >> lastName[i] >> workorder[i] >> mechanic[i];
            cout << firstName[i] << endl  << lastName[i] << endl << workorder[i] << endl << mechanic[i] << endl;
      }

      for (i=0; i < count; i++)
      {
            strcpy(car[i],lastName[i]);
              strcat(car[i]," , ");
        strcat(car[i],firstName[i]);
       
            cout << workorder[i] << " ";
      }
      cout << endl;
      for (i=0; i < count; i++)
      {
            cout << car[i] << endl;;
      }

      cout << endl;
      sort(car, workorder, mechanic, count);
            
}

//******************************************************
//This is the sort function that I can't seem to get to
//work properly.  The workorder integer array sorts
//fine, but I can't seem to get my two arrays of strings
//to sort properly
//******************************************************
void sort(nameString a[], int b[], nameString c[], int d)
{
      int pass;
      int i;
      int hold[50];
      typedef char stg[20];
      stg hold2[50];
      stg hold3[50];
      stg newhold2[50];
      
      for (i=0; i<d; i++)
      {
            strcpy(hold2[i], a[i]);
      }

      cout << "This is the contents of array hold2" << endl;
      for (i=0; i<d; i++)
      {
            cout << hold2[i] << endl;
      }      
      
      cout << endl << endl << endl;
      
      for(pass=0; pass<d-1; pass++)
            for (i=0; i<d-1; i++)
                  if (b[i] > b[i+1])
                  {
                        hold[i] = b[i];
                        b[i] = b[i+1];
                        b[i+1] = hold[i];

                        //**************************
                        //This is where I am getting
                        //stuck
                        //**************************
                        strcpy(hold2[i+1], a[i]);
                        strcpy(a[i], a[i+1]);
                        strcpy(a[i+1], hold2[i]);

                        strcpy(hold3[i+1], c[i]);
                        strcpy(c[i], c[i+1]);
                        strcpy(c[i+1], hold3[i]);
                  }
                  
      for (i=0; i < d; i++)
      {
            cout << b[i] << endl;
            
            
      }

      cout << "This is the contents of the hold2 array after the sort:"  << endl << endl;


      for (i=0; i < d; i++)
      {
            cout << hold2[i] << endl;
            
            
      }

      
}


0
Comment
Question by:samford
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 4

Expert Comment

by:chaos_hooi
ID: 8055445
Even though you did extra steps, your sort should work, assuming the typedef works (I forgot how typedef work)... Why are you checking the contents of hold2 at the end anyway? Shouldn't you be checking the contents of a[] and c[]?

Here are my comments...
1) It is pointless to declare hold1, hold2, hold3 as arrays, as you are only to use them as temporary variable when you are swapping the value.
2) When you are doing this sort of swapping, you will automatically move the largest value to the end during the first inner loop end, so it is pointless to compare the last value again during your second inner loop.
0
 
LVL 2

Expert Comment

by:bkrahmer
ID: 8055888
I don't like the typedefs.  They scare me.  I think you meant 'typedef char[20] nameString'.  Either way, I would get rid of the char type, and use STL strings.  You should also consider reading the data into objects.  I really don't understand what you're trying to do with the sorting.

brian
0
 

Expert Comment

by:mnf
ID: 8055912
I'd spend a little more time setting up - group together the connected data.  Then we only have to sort one array and life is a little less complicated later on.


//---------------------------------------------------------------------------

#pragma hdrstop

#include <string>        // I'll use string insead of char*
#include <vector>       // And use vector (more flexible) instead of an array
#include <algorith>     // for the sort algorithm
#include <iostream>     // Input / Output
#include <fstream>      // Read list of cars from a file

using namespace std;    // The standard library namespace

class Car               // Group together the related bits (or use a struct)
{
        public:
                string name, make, mechanic;
                bool operator<(const Car &rhs) const;           // Compare by name
};

bool Car::operator<(const Car &rhs) const
{                                       // Order as required (eg make case insensitive)
        return name < rhs.name;
}

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
        int i;
        vector<Car> cars;            // For now a fixed array of 7 cars
        fstream input("cars.txt");      // open our input file
        do                           // Read in some test data
        {
                Car test;
                input >> test.name >> test.make >> test.mechanic;
                if(input.eof()) break;
                cars.push_back(test);   // Add car to the vector
        } while(true);

        sort(cars.begin(), cars.end());         // Sort them!!

        for(i = 0; i < cars.size(); ++i)        // Display the results
                cout << cars[i].name << " " << cars[i].make << " " << cars[i].mechanic << endl;
        getchar();
        return 0;
}
//---------------------------------------------------------------------------
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:mnf
ID: 8055924
I'd spend a little more time setting up - group together the connected data.  Then we only have to sort one array and life is a little less complicated later on.


//---------------------------------------------------------------------------

#pragma hdrstop

#include <string>        // I'll use string insead of char*
#include <vector>       // And use vector (more flexible) instead of an array
#include <algorith>     // for the sort algorithm
#include <iostream>     // Input / Output
#include <fstream>      // Read list of cars from a file

using namespace std;    // The standard library namespace

class Car               // Group together the related bits (or use a struct)
{
        public:
                string name, make, mechanic;
                bool operator<(const Car &rhs) const;           // Compare by name
};

bool Car::operator<(const Car &rhs) const
{                                       // Order as required (eg make case insensitive)
        return name < rhs.name;
}

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
        int i;
        vector<Car> cars;          
        fstream input("cars.txt");      // open our input file
        do                           // Read in some test data
        {
                Car test;
                input >> test.name >> test.make >> test.mechanic;
                if(input.eof()) break;
                cars.push_back(test);   // Add car to the vector
        } while(true);

        sort(cars.begin(), cars.end());         // Sort them!!

        for(i = 0; i < cars.size(); ++i)        // Display the results
                cout << cars[i].name << " " << cars[i].make << " " << cars[i].mechanic << endl;
        getchar();
        return 0;
}
//---------------------------------------------------------------------------
0
 
LVL 4

Expert Comment

by:chaos_hooi
ID: 8056003
'typedef char[20] nameString'

Now, that makes more sense... Once you do a typedef outside the functions, it is known globally, so you don't have to do typedef too inside the functions... Get rid of all those typedefs in the functions! Get rid of all the hold arrays and replace that with a temp variable of nameString type and integer type (for working order):

int tmp;
nameString temp;

Replace all those swaps with:

  tmp = b[i];
  b[i] = b[i+1];
  b[i+1] = tmp;

  strcpy(temp, a[i]);
  strcpy(a[i], a[i+1]);
  strcpy(a[i+1], temp);

  strcpy(temp, c[i]);
  strcpy(c[i], c[i+1]);
  strcpy(c[i+1], temp);

Here are some of the stuffs that you need to change and understand in your main function:

  nameString mechanic[50];
  // Last and First names of at most 50 mechanics.
  // YOU NEED TO STRING CONCATENATE LAST AND
  // FIRST NAME HERE, NOT car[50].

  nameString firstName[50];
  // First names of at most 50 mechanics

  nameString lastName[50];              
  // Last names of at most 50 mechanics

  nameString car[50];
  // Name/model of at most 50 cars.
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8056004
>>>build a small database of cars and then query the >>>database by certain criteria.
>>>are actually three main arrays that I have built:  one >>>containing strings of the the cars make and model, one >>>containing the work order number which is an array of >>>integer and one containing strings of the mechanics last names

that means a single entry of ur database will have  cars make and model , work order number and mechanics last name
well then u must group the elements in single struct
like this

#define MAXENTRY 32
typedef nameString[20];
typedef struct _entry{
nameString  carmodel;
int         orderNo;
nameString  mechanic;
}entry;

entry entries[MAXENTRY];

also i would suggest that u shud use standard librarie's qsort function .. u need to provide a comparator function.. and it can sort any stuff..
yea that only if sorting is not promary goal .. if u wish to implement ur own sorting routine then go ahead with ur function .. but still i wud suggest grouping up of the data like i suggested
0
 
LVL 3

Expert Comment

by:EarthQuaker
ID: 8071247
*YUCK*

Let's code in C++ :

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
  vector<string> vStr;
  vStr.push_back("sort method");
  vStr.push_back("efficient");
  vStr.push_back("a");
  sort(vStr.begin(), vStr.end());
  copy(vStr.begin(), vStr.end(), ostream_iterator<string>(cout, " "));
  return 0;
}




What is printed is : "a efficient sort method"
0
 
LVL 3

Accepted Solution

by:
EarthQuaker earned 400 total points
ID: 8071251
Add a "using namespace std;" between "#include <algorithm>" and "int main()"
0
 

Author Comment

by:samford
ID: 8085526
Thanks for the help Earthquaker!
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question