?
Solved

Sorting Arrays of Strings

Posted on 2003-03-02
9
Medium Priority
?
287 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.

752 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