Thread: Searching Array (Help Please)

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    19

    Question Searching Array (Help Please)

    Okay, now that I go all of my sorting of the array out of my way, I am into a new problem with this stupid program, and I really need help ASAP please! I am trying to search the array of employees by last name and display the employee that was searched with all of their data. Could someone please help me here!!!

    All of my code:
    Code:
    /******************************************************
    
    ** Name: Joshua Long
    
    ** Filename: CPP_FINAL1.cpp
    
    ** Project Description: Enter the number of employees you want
       to input into the database, enter all of the employees and
       then sort the employees by last name. Prompt user to search
       for an employee by last name then display employee.
    
    ** Output: Employee data that was entered and then organized
       by the program to have better formatting.
    
    ** Input: Employee data
    
    ** Strees Level: Very HIGH ;)
    
    ******************************************************/
    
    // Include Files
    #include <iostream> // used for cin, cout
    #include <iomanip>
    #include <string.h>
    #include <stdio.h> 
    using namespace std;
    
    // Search Array
    void searchString(string A[],int size, string answer) {
         int j;
         for(j=0; j < size; j++)
         if(A[j] == answer)
                 cout << A[j] << endl;
         else cout << "Not Found"<< endl;
    }
    
    const int MAX_NAME_SIZE = 22; // Max size for names
    const int MAX_SIZE = 25; // Max size for all other strings
    
    // Employee Structure (Used for all employees
    struct Employee {
           // Chars used instead of strings for use of spaces
           char eName[MAX_NAME_SIZE], eLName[MAX_NAME_SIZE], eStreetName[MAX_SIZE], eCity[MAX_SIZE], eState[MAX_SIZE]; 
           int eID, eStreetNum, eZip;
           void inNameeID();
    };
    
    
    // Max amount of employees allowed in program
    const int MAX_EmployeeS = 50;
    
    // The Employees class
    class Employees {
          public:
                 // Fuction Prototypes
                 void inEmployees();
                 void inNameeID();
                 void sortNameeID();
                 void print(const char *prompt);
                 
                 // Private variables
                 private:
                         Employee data[MAX_EmployeeS];
                         int size;
    };
    
    
    // Main Processing
    int main() {
        //xEmployee.print("Original list"); // Used to print original
        //xEmployee.print("Alphabetized list"); // Used to print aplha list
        
        // Create new instance of Employees (stores all employee's data)
        Employees xEmployee;
        
        // Display which employee is being input
        xEmployee.inEmployees();
        // Prompt for input of the employee data and display entered results
        xEmployee.inNameeID();
        xEmployee.print("Initial Employee Data");
        
        // Sort the employee data by last name
        xEmployee.sortNameeID();
        // Print the employees that have been entered
        xEmployee.print("Sorted Employee List"); 
        cout << endl << endl; // Skip a few lines after list displayed
        
        string target = "";
        cout << "Please enter last name to search for: ";
        cin >> target; cin.ignore();
        
        // Search Array for target
        searchString(ARRAY GOES HERE, MAX_EmployeeS-1, target);
        
        //Pause program before shutting down
        system("PAUSE");
            
    }
    
    
    // Prompt for the user input on the employee's data
    void Employee::inNameeID() {
            cout << "First Name: ";
            cin.getline( eName, MAX_NAME_SIZE); // First Name
            cout << "Last Name: ";
            cin.getline( eLName, MAX_NAME_SIZE); // Last Name
            cout << "Street Number: ";
            cin >> eStreetNum; cin.ignore(); // Street Number
            cout << "Street Name: ";
            cin.getline( eStreetName, MAX_SIZE); // Street Name
            cout << "City: ";
            cin.getline( eCity, MAX_SIZE); // City
            cout << "State: ";
            cin.getline( eState, MAX_SIZE); // State
            cout << "Zip Code: ";
            cin >> eZip; cin.ignore(); // Zip Code
            cout << "Customer ID: ";
            cin >> eID; cin.ignore();  // Customer ID
            cout << endl;
    }
    
    
    // Prompt for how many employees should be entered
    void Employees::inEmployees() {
            cout << "Enter number of Employees (1 . . " << MAX_EmployeeS << ")" << endl << '>';
            cin >> size; cin.ignore(); 
    }
    
    
    // Display which employee is being entered
    void Employees::inNameeID() {
            for ( int count = 0; count < size; count++ ) {
                    cout << "Employee " << (count + 1) << endl;
                    data[count].inNameeID();
            }
    }
    
    
    // Print the employees that have been entered
    void Employees::print(const char *prompt) {
            cout << prompt << endl;
            cout << "------------------------------" << endl;
            for ( int count = 0; count <size; count++ ) {
                    cout << data[count].eLName << ", " << data[count].eName  << "\n"; // Last Name, First Name
                    cout << data[count].eStreetNum << " " << data[count].eStreetName << "\n"; // Street Number Street Name
                    cout << data[count].eCity << ", " << data[count].eState << " " << data[count].eZip << "\n"; // City, State Zip
                    //cout << setw( 8 ) << left << "Customer ID: " <<data[count].eID << "\n"; // Customer ID
                    cout << endl;
            }
            cout << endl;
    }
    
    
    // Sort fuction used to sort through the employee struct and sort by last name else, customer ID
    void Employees::sortNameeID() {
             int smallestOrLargest;
             int index;
             
             for ( int i = 0; i < size-1; i++ ) {
                    int smallestOrLargest = i;
                     
                    for ( int index = i + 1; index < size; index++ ) {
                            int cmpName = strcmp(data[index].eLName, data[smallestOrLargest].eLName);
                            if (cmpName<0) { smallestOrLargest = index;
                            } else if (cmpName==0) { // names match
                                    if (data[index].eID<data[smallestOrLargest].eID) {
                                            smallestOrLargest = index;
                                    }
                            }
                    }
                    
                    if (smallestOrLargest != i) { //swap them
                            Employee temp = data[i];
                            data[i] = data[smallestOrLargest];
                            data[smallestOrLargest] = temp;
                    }
            }
    }
    Thanks in advance if anyone can help! I have the function to search, but if there is another way to do this, then please help me!!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    So make your search function a member of your class, then it can have access to your data array.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Oh, you started another thread. You should probably have continued your other one. I just wrote a bunch of stuff in there. Only start a new one if it is about a completely separate thing, or several weeks have passed with no activity in the thread.

    In this instance you should put braces around your for loop statements so that you can see what is actually going on:
    Code:
    for(j=0; j < size; j++) {
        if(A[j] == answer)
            cout << A[j] << endl;
        else
            cout << "Not Found"<< endl;
    }
    How many times is "Not Found" going to be shown? Does that make the problem obvious?
    The trick is that you shouldn't use an else here. Instead, when you find the thing your after you return from the function immediately. Then if you loop ends and you're thus still inside the function, it must have failed to find the item, so...

    Again you're taking an array of strings as a parameter to a function, but you have no array of strings, only an array of Employee. Same hint as last time.
    Incidentally if would be great if you had used strings inside of employee instead of char arrays, but that's beside the point.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    19
    I used the chars so that I could store the spaces that the strings weren't storing inside the output. So like for the City it could be: Some Town. With the strings, it would think that Some was the City, and Town was the State...it was really annoying me.

    as for the searching function, am I going about it in a right fashion, or could you help me here. I tried putting it into my class and it still is saying that data is undefined...this is annoying and I need it done by this afternoon. Could someone please give the code with a step-through of how it is supposed to be? Please?

  5. #5
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    the undefined part might refer to your use of the const to define your array size, in this case your compiler does not like it, i bet if you put in the number directly to define the size of your array that error will stop
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    19
    No, that isn't it...it keeps giving me the error that my array isn't defined...this is so stupid!! I really need help!

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    This is a direct extract from your code (I'd guess about 80-90 lines in)

    Code:
        // Search Array for target
        searchString(ARRAY GOES HERE, MAX_EmployeeS-1, target);
    Clearly whoever gave you this code expected you to do some work rather than doing your homework for you. Provide the name of an actual array in place of the text "ARRAY GOES HERE" and your compiler might stop moaning.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    All I can say is you need to change your attitude.

    1) You communicate with a sequence of vague whines rather than trying to formulate a real question in terms of C/C++ syntax, etc.
    2) Probably this is because you cannot be bothered to even attempt formulating such a question.
    3) Probably that is because you are LAZY.

    Throwing up a pile of code, then expecting people to test one part of it and maybe re-write it for you is stupid. Why don't you take a few deep breaths, think about what specifically your problem is, then try and write a *seperate* *short* program to either demonstrate clearly the issue or (better yet, and I promise, the chances are good...) allowing you to experiment and explore the problem yourself, because if you cannot do that, then you cannot rationalize or abstract and should give up programming right now.

    Quote Originally Posted by grumpy View Post
    Clearly whoever gave you this code expected you to do some work rather than doing your homework for you. Provide the name of an actual array in place of the text "ARRAY GOES HERE" and your compiler might stop moaning.
    Point in fact.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    19
    *Sigh*...thank you for stating that I am lazy and can't come up with things on my own...the exclamation marks are just because I am frustrated...

    I am not trying to come off as mean, I am just in a big predicament here and I really need some help on this. That is why I asked if someone could step through this for me so I can understand how a search function could work in this.

    Yes, my code says that the array goes here, but I put that up here so that you guys knew where I was putting the array, which by the way wasn't working. I am not sure why my array, data[] wasn't working with it when I even put it into the class...I am trying different things, but any help would be nice.

    Sorry for coming off as mean, lazy, and all that...I have been working on this program for 3 days now, and I am almost done, but I am in need of finishing this searching function...

    PS.- I did figure out my sorting function, and that was so difficult, but I did get it with an algorithm help. I am just having a hard time finding what needs to be done for this search function.

    Sorry again. Could someone please help step this through for me?

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    19
    Alright, so, this is what I am trying to do so I can use my data[] array, but I am going to need some help with how it works.

    Here is my code for the Employee Class:
    Code:
    // The Employees class
    class Employees {
          public:
                 // Fuction Prototypes
                 void inEmployees();
                 void inNameeID();
                 void sortNameeID();
                 void print(const char *prompt);
                 
                 // Private declarations
                 private:
                              Employee data[MAX_EmployeeS];
                              int size;
                              
                              // Search Array
                              void searchEmployees(string A[],int size, string target) {
                                   int j;
                                   for(j=0; j < size; j++){
                                            if(A[j] == target){
                                                    cout << A[j] << endl;
                                                    }
                                   }
                              };
    
    };
    Here is my calling function:
    Code:
        string target = "";
        cout << "Please enter last name to search for: ";
        cin >> target; cin.ignore();
        
        searchEmployees(data, size, target);
    I want to be able to use the data[] array because that is what is being used in my sorting function. The size variable is the size of the array, and the target variable is being used to store what is being searched for.

    It would be a greatly appreciated help if someone can help. Sorry for all the confusion and being impatient! :P Not trying to sound like I am yelling here.

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Can you posted the updated code please. After making suggestiong and giving hints, we need to see what changes were actually made in order to know what to suggest next. You can skip large parts that weren't changed if you like.
    Edit: Sorry cross-posted.

    MK27, it's not necessarily laziness. Some people have a personality type where sympathy becomes as important or more so than the actual assistance, and this leads to them being rather vague about the actual problem. Admittedly it's not productive from the point of view of most of us here, but I think you'll appreciate that most of us do better when we are happy, and for some the affect is greater than in others. Make sure your criticism is constructive I guess.
    This person is trying, they're just not as good as helping themselves to be helped as some are.
    Last edited by iMalc; 05-14-2010 at 06:46 PM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Do you mean for search to be private? That means that things outside the class can't access it.
    How about just putting a function prototype in the class, and then putting the definition outside, like you have with your other functions?
    Organisationally, this needn't be much different from inNameeID or your other functions.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  13. #13
    Registered User
    Join Date
    May 2010
    Posts
    19
    Alright, here is the new function, but I am still getting errors.

    Class:
    Code:
    // The Employees class
    class Employees {
          public:
                 // Fuction Prototypes
                 void inEmployees();
                 void inNameeID();
                 void sortNameeID();
                 void print(const char *prompt);
                 void searchEmployees(string A[],int size, string target);
                 
                 // Private declarations
                 private:
                              Employee data[MAX_EmployeeS];
                              int size;
    };
    The Search Function:
    Code:
    // Search Array
    void Employee::searchEmployees(string A[],int size, string target) {
         int j;
         for(j=0; j < size; j++){
                  if(A[j] == target){
                  cout << A[j] << endl;
                  }
         }
    }
    Calling:
    Code:
        string target = "";
        cout << "Please enter last name to search for: ";
        cin >> target; cin.ignore();
        
        xEmployee.searchEmployees(data, size, target);
    I am still getting the error that data[] and size are not defined...This is with the new updated code:

    Code:
    /******************************************************
    
    ** Name: Joshua Long
    
    ** Filename: CPP_FINAL1.cpp
    
    ** Project Description: Enter the number of employees you want
       to input into the database, enter all of the employees and
       then sort the employees by last name. Prompt user to search
       for an employee by last name then display employee.
    
    ** Output: Employee data that was entered and then organized
       by the program to have better formatting.
    
    ** Input: Employee data
    
    ** Strees Level: Very HIGH ;)
    
    ******************************************************/
    
    // Include Files
    #include <iostream> // used for cin, cout
    #include <iomanip>
    #include <string.h>
    #include <stdio.h> 
    using namespace std;
    
    const int MAX_NAME_SIZE = 22; // Max size for names
    const int MAX_SIZE = 25; // Max size for all other strings
    
    // Employee Structure (Used for all employees
    struct Employee {
           // Chars used instead of strings for use of spaces
           char eName[MAX_NAME_SIZE], eLName[MAX_NAME_SIZE], eStreetName[MAX_SIZE], eCity[MAX_SIZE], eState[MAX_SIZE]; 
           int eID, eStreetNum, eZip;
           void inNameeID();
    };
    
    
    // Max amount of employees allowed in program
    const int MAX_EmployeeS = 50;
    
    // The Employees class
    class Employees {
          public:
                 // Fuction Prototypes
                 void inEmployees();
                 void inNameeID();
                 void sortNameeID();
                 void print(const char *prompt);
                 void searchEmployees(string A[],int size, string target);
                 
                 // Private declarations
                 private:
                              Employee data[MAX_EmployeeS];
                              int size;
    };
    
    
    // Main Processing
    int main() {
        //xEmployee.print("Original list"); // Used to print original
        //xEmployee.print("Alphabetized list"); // Used to print aplha list
        
        // Create new instance of Employees (stores all employee's data)
        Employees xEmployee;
        
        // Display which employee is being input
        xEmployee.inEmployees();
        // Prompt for input of the employee data and display entered results
        xEmployee.inNameeID();
        xEmployee.print("Initial Employee Data");
        
        // Sort the employee data by last name
        xEmployee.sortNameeID();
        // Print the employees that have been entered
        xEmployee.print("Sorted Employee List"); 
        cout << endl << endl; // Skip a few lines after list displayed
        
        string target = "";
        cout << "Please enter last name to search for: ";
        cin >> target; cin.ignore();
        
        xEmployee.searchEmployees(data, 50, target);
        
        //Pause program before shutting down
        system("PAUSE");
            
    }
    
    // Search Array
    void Employee::searchEmployees(string A[],int size, string target) {
         int j;
         for(j=0; j < size; j++){
                  if(A[j] == target){
                  cout << A[j] << endl;
                  }
         }
    }
    
    // Prompt for the user input on the employee's data
    void Employee::inNameeID() {
            cout << "First Name: ";
            cin.getline( eName, MAX_NAME_SIZE); // First Name
            cout << "Last Name: ";
            cin.getline( eLName, MAX_NAME_SIZE); // Last Name
            cout << "Street Number: ";
            cin >> eStreetNum; cin.ignore(); // Street Number
            cout << "Street Name: ";
            cin.getline( eStreetName, MAX_SIZE); // Street Name
            cout << "City: ";
            cin.getline( eCity, MAX_SIZE); // City
            cout << "State: ";
            cin.getline( eState, MAX_SIZE); // State
            cout << "Zip Code: ";
            cin >> eZip; cin.ignore(); // Zip Code
            cout << "Customer ID: ";
            cin >> eID; cin.ignore();  // Customer ID
            cout << endl;
    }
    
    
    // Prompt for how many employees should be entered
    void Employees::inEmployees() {
            cout << "Enter number of Employees (1 . . " << MAX_EmployeeS << ")" << endl << '>';
            cin >> size; cin.ignore(); 
    }
    
    
    // Display which employee is being entered
    void Employees::inNameeID() {
            for ( int count = 0; count < size; count++ ) {
                    cout << "Employee " << (count + 1) << endl;
                    data[count].inNameeID();
            }
    }
    
    
    // Print the employees that have been entered
    void Employees::print(const char *prompt) {
            cout << prompt << endl;
            cout << "------------------------------" << endl;
            for ( int count = 0; count <size; count++ ) {
                    cout << data[count].eLName << ", " << data[count].eName  << "\n"; // Last Name, First Name
                    cout << data[count].eStreetNum << " " << data[count].eStreetName << "\n"; // Street Number Street Name
                    cout << data[count].eCity << ", " << data[count].eState << " " << data[count].eZip << "\n"; // City, State Zip
                    //cout << setw( 8 ) << left << "Customer ID: " <<data[count].eID << "\n"; // Customer ID
                    cout << endl;
            }
            cout << endl;
    }
    
    
    // Sort fuction used to sort through the employee struct and sort by last name else, customer ID
    void Employees::sortNameeID() {
             int smallestOrLargest;
             int index;
             
             for ( int i = 0; i < size-1; i++ ) {
                    int smallestOrLargest = i;
                     
                    for ( int index = i + 1; index < size; index++ ) {
                            int cmpName = strcmp(data[index].eLName, data[smallestOrLargest].eLName);
                            if (cmpName<0) { smallestOrLargest = index;
                            } else if (cmpName==0) { // names match
                                    if (data[index].eID<data[smallestOrLargest].eID) {
                                            smallestOrLargest = index;
                                    }
                            }
                    }
                    
                    if (smallestOrLargest != i) { //swap them
                            Employee temp = data[i];
                            data[i] = data[smallestOrLargest];
                            data[smallestOrLargest] = temp;
                    }
            }
    }

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by iMalc View Post
    MK27, it's not necessarily laziness. Some people have a personality type where sympathy becomes as important or more so than the actual assistance, and this leads to them being rather vague about the actual problem. Admittedly it's not productive from the point of view of most of us here, but I think you'll appreciate that most of us do better when we are happy, and for some the affect is greater than in others. Make sure your criticism is constructive I guess.
    Yeah I'm kind of in groucho mood, or was, all apologies...I don't have time to be compiling and decyphering this, so I just wanted to indicate there is a "better" way. All in good time I guess.

    @RadethDart: would help if you indicate where/when you are being told you have these undefined variables (eg, the line number, and indicate that line).
    Last edited by MK27; 05-14-2010 at 07:04 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by MK27 View Post
    @RadethDart: would help if you indicate where/when you are being told you have these undefined variables (eg, the line number, and indicate that line).
    Actually it's not hard to see, just a lot of clutter in the way:
    Code:
    // Main Processing
    int main() {
         Employees xEmployee;
        
        // Display which employee is being input
        xEmployee.inEmployees();
        // Prompt for input of the employee data and display entered results
        xEmployee.inNameeID();
        xEmployee.print("Initial Employee Data");
        
        // Sort the employee data by last name
        xEmployee.sortNameeID();
        // Print the employees that have been entered
        xEmployee.print("Sorted Employee List"); 
        cout << endl << endl; // Skip a few lines after list displayed
        
        string target = "";
        cout << "Please enter last name to search for: ";
        cin >> target; cin.ignore();
        
        xEmployee.searchEmployees(data, 50, target);
    That is the first time "data" is mentioned, so of course it is undefined.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. warning: excess elements in array initializer
    By redruby147 in forum C Programming
    Replies: 6
    Last Post: 09-30-2009, 06:08 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  3. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. searching thru a c++ class array
    By stanleyw in forum C++ Programming
    Replies: 1
    Last Post: 05-29-2002, 09:15 PM