Solved

Inserting elements into an array of a class..

Posted on 2003-11-18
5
328 Views
Last Modified: 2010-04-01
Here is the question..  I need to insert another voter into the array using a function.  The program starts out by reading an input file and stores it in an array of the voter class.. Have that working all.. I am having the worst time trying to write a function to add onto that array from user input.

I dont want the answer just some idea what i need to do...   I currently go to university of buffalo and as of an elective the make us take cs121

#include "fileutil.cpp"

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<string.h>
#include<ctype.h>
#include<fstream.h>

#if !defined(microsoft)
#include<stdlib.h>
#define cls() system("cls");
#endif

//*****************************************************************************
// Beginning of Voter Class                                                   *
//*****************************************************************************

class Voter
{
      private:
            int idnumber;
            char lastname[25];
            char firstname[25];
            char party[2];
            int birthyear;
            int currentage;

      public:
            Voter();
            Voter(int,char[], char[], char[], int, int);
            Voter(const Voter&);
            void read();
            void operator =(const Voter&);
            void print();
            ~Voter();
};

//*****************************************************************************
// Default Constructor                                                        *
//*****************************************************************************

Voter::Voter()
{
      idnumber = 0;
      lastname[0] = '\0';
      firstname[0] = '\0';
      party[2] = '\0';
      birthyear = 0;
      currentage = 0;
}

//*****************************************************************************
// Constructor Arguments                                                      *
//*****************************************************************************

Voter::Voter(int id,char ln[], char fn[], char pid[], int year, int by)
{
      idnumber = id;
      strcpy(lastname, ln);
      strcpy(firstname, fn);
      strcpy(party, pid);
      birthyear = year;
      currentage = 2003 - birthyear;
}

//*****************************************************************************
// Copy Constructor                                                           *
//*****************************************************************************

Voter::Voter(const Voter& v1)
{
      idnumber = v1.idnumber;
      strcpy(lastname, v1.lastname);
      strcpy(firstname, v1.firstname);
      strcpy(party, v1.party);
      birthyear = v1.birthyear;
      currentage = 2003 - v1.birthyear;
}

//*****************************************************************************
// Get Voter Information                                                      *
//*****************************************************************************

void Voter::read()
{
      cls();
      char trash[2];
      
      cout<<"Enter your voter id number: "<<endl;
      cin >> idnumber;
      
      cout<<"Enter your last name: " << endl;
      cin.getline(trash,2);
      cin.getline(lastname, 25);

      cout<<"Enter your first name: " << endl;
      cin.getline(firstname, 25);

      cout<<"Enter your party id letter: " << endl;
      cin>>party;

      cout<<"Enter your birth year: " << endl;
      cin>>birthyear;

      currentage = 2003 - birthyear;
}

//*****************************************************************************
// Assignment Operator                                                        *
//*****************************************************************************

void Voter::operator =(const Voter& v1)
{
      idnumber = v1.idnumber;
      strcpy(lastname, v1.lastname);
      strcpy(firstname, v1.firstname);
      strcpy(party, v1.party);
      birthyear = v1.birthyear;
      currentage = 2003 - v1.birthyear;
}

//*****************************************************************************
// Print List of Voters                                                       *
//*****************************************************************************

void Voter::print()
{
      cout << idnumber    << setw(12)
              << lastname    << setw(12)
             << firstname   << setw(12)
           << party       << setw(12)
             << birthyear      << setw(12)
             << currentage  << setw(12)
         << endl;
}

//*****************************************************************************
// Destructor                                                                 *
//*****************************************************************************

Voter::~Voter()
{

}

//*****************************************************************************
// Prototye Declaration                                                       *
//*****************************************************************************

void PrintList(Voter voterlist[], int);
void ReadData(Voter voterlist[], int&);
int Display_Menu(int);

//*****************************************************************************
// Main Body of Propgram                                                       *
//*****************************************************************************

void main()
{



      
      
Voter voterlist[8];
int error = 0;

ReadData(voterlist,error);
cls();


PrintList(voterlist, error);
cout << endl; // just using these to lines while testing program...
getche();        //




}


//*****************************************************************************
// Function Name: Display_Menu
// Purpose: This purpose of this function is to display the main menu of this
//          program to the terminal screen.  Then the user will enter there the
//          selection.
//
// Parameters:
//   Input:
//   Input & Output:
// Return Value: choice
// Non-local Variables Used: choice
// Functions Called:iomanip - setw

//*****************************************************************************

int Display_Menu(int choice)
{
      cls();
    cout << setw(25) << "\n ========== Menu Selection Screen ============= \n";
      cout << setw(25) << "\n   [1] Display voters to display                  ";
      cout << setw(25) << "\n   [2]                                                     ";
      cout << setw(25) << "\n   [3]                                                         ";
      cout << setw(25) << "\n   [4]                                            ";
      cout << setw(25) << "\n   [5]                                            ";
      cout << setw(25) << "\n   [6] Exit Program                             \n";
      cout << setw(25) << "\n ============================================== \n"  
             << endl;
      
            cout << setw(22) << "Enter Selection >  ";
            cin  >> choice;

      return choice;

}

//*****************************************************************************
// Function Name: ReadData
// Purpose: The purpose of this function is to read in values from a txt file
//          supplied by the teacher. This function will read in whitespace and
//          check for errors.
//
// Parameters:
//   Input:
//   Input & Output:
// Return Value: choice
// Non-local Variables Used:
// Functions Called:

//*****************************************************************************

void ReadData(Voter voterlist[], int& error)
{

      int  age,
             idnumber,
             birthyear,
             currentage = 0,
             numVoters  = 0;

      char lastname[25],
             firstname[25],
             party[2],
             trash[2];

      ifstream infile;
      ofstream outfile;


      OpenInput( infile, "Give name of Data File:  " );

      while (infile.good() )
      {
            infile >> idnumber;
            infile.getline(trash,2);
            infile.getline(lastname,25,'\t');
            infile.getline(firstname, 25, '\t');
            infile.getline(party, 2, '\t');
            infile >> birthyear;

            age = 2003 - birthyear;


if ((strcmp(party, "r") == 0) || (strcmp(party, "R") == 0) ||
      (strcmp(party, "d") == 0) || (strcmp(party, "D") == 0) ||
      (strcmp(party, "l") == 0) || (strcmp(party, "L") == 0) ||
      (strcmp(party, "c") == 0) || (strcmp(party, "C") == 0))
{
      
      if ((idnumber > 1000) && ( idnumber < 10000))
      {
            
            if ((age > 17) && (age < 126))
            {
                  voterlist[numVoters] = Voter(idnumber,lastname, firstname, party, birthyear, currentage);
                  ++ numVoters;
            }
            else
                error++;
      }
      else
            error++;
}
else
      error++;

if (infile.fail())
break;

}
infile.close();
}

//*****************************************************************************
// Function Name: PrintList
// Purpose:Prints Voter information to display.
//
// Parameters:
//   Input:
//   Input & Output:
// Return Value: choice
// Non-local Variables Used:
// Functions Called:

//*****************************************************************************

void PrintList(Voter voterlist[], int error)
{

      for (int n = 0;n<(8 - error) ;n++)
      {
            voterlist[n].print();
      }
}

//*****************************************************************************
// Function Name:
// Purpose:Prints:
//
// Parameters:
//   Input:
//   Input & Output:
// Return Value: choice
// Non-local Variables Used:
// Functions Called:

//*****************************************************************************

0
Comment
Question by:rbran1974
5 Comments
 
LVL 16

Expert Comment

by:George Tokas
Comment Utility
Without checking your code....
why you can do this:
userinput will store the data on the file.
reload the file using the same way in your startup.

Regards,

gtokas.
0
 
LVL 11

Accepted Solution

by:
bcladd earned 200 total points
Comment Utility
(1) Some suggestions to make your code easier to read/write:

(a) Use istream.ignore: Right now you use getline(trash). Your intention would be clearer to a reader if, where you now read trash (and ignore it) you had something like the following:
    infile.ignore(2, '\n'); // ignore the next two characters or up to an end-of-line

(b) Using 17 and 126 as "magic numbers" in your program makes it hard to change these values. If the voting age drops to 16 then you must go through your program, find every > 17 and figure out if it refers to minimum voting age. It would be clearer to use constants. At the global scope declare

    const int MINIMUM_VOTING_AGE = 18;

Then you can compare the age with the minimum voting age with:

    if (age >= MINIMUM_VOTING_AGE) { .... }

Makes the code "self documenting".

(2) Reading information from the user: Your member function Voter::read() looks like it contains the code you want to use. You want to write a global function, however, similar to ReadData that updates all the associated information (the number of elements in the array, for example). So if the user selects "add" from the menu you call ReadDataFromUser. The body of this function looks like a cross between your Voter::read and ReadData functions. Make sure you pass the array and the integer into the function so the size of the list is updated.

I am not providing code because this seems to be homework and we are not allowed to write homework for you. We can answer specific questions so come on back and ask some.

-bcl
0
 
LVL 9

Expert Comment

by:jhshukla
Comment Utility
I haven't read you code and do not intend to do so. but here's what you can do. (this is only a breakdown of the large problem into parts. start thinking that way :-)
> write a comparator function for Voter class. if you have done good! (you only need == unless you are sorting)
> in the default constructor specify some specific value for each field that are always invalid for a real life voter like age=-1;
> when you want to insert a voter in your array, search linearly till you find a default/empty Voter element. insert your new Voter at the end.

As a good practice return a "true" from the function if insertion is successful and "false" if the array is full. or you can also return the number of empty spaces left in the array. This returning value part is not that relevant.

Hopethe problem looks much simpler now that it is broken down into parts.
and bcl has given you some really good sugesstions. follow tham and thank him/her.

j
0
 
LVL 9

Expert Comment

by:tinchos
Comment Utility
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: bcladd {http:#9772538}

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now