Try to delete an element from array, always deletes last element no matter what.

what am I doing wrong here I just want to delete selected record. I can select any record and it will always delete last one.. my delete voter is the last function.

code:


#include "fileutil.cpp" // Used to read and write files

#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

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 Add();
      void Edit();
      void operator = (const voter&);
      void print(int);
      void disksave(ofstream& outfile);
      ~voter();

};


// =========================== Default Constructor =================================

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


// =========================== Constructor with 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;
}


// =========================== 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;
}

// =========================== Add Voter   ================================

void voter::Add()
{

      cls();
      int age =0;

      char trash[2];
      
      cout<<"Enter your voter id number: ";
      cin >> idnumber;

      while ((idnumber < 1000) || // Loop that validates voter
              ( idnumber > 10000))  // id number.

      {      
            cls();
            cout << "Valid ID number is between 1000 and 10000"
                   << endl << endl;

            cout << "Please enter a valid voter id number > ";
            cin  >>  idnumber;
            cout << endl;
      }

      cout<<"Enter your last name: ";
      cin.getline(trash,2);
      cin.getline(lastname, 25);

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

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

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

      while((birthyear < 1878) || (birthyear > 1985))
      {
      
            cls();
            age = 2003 - birthyear;
      
      
            cout << " You must be atleast 18 yrs. old to vote!!"
                   << endl;
            cout << " Your current age: " << age << endl;



            cout << "\n Please enter a valid birth year: ";
            cin  >> birthyear;
      }

      currentage = 2003 - birthyear;      
}


// =========================== Edit Voters Party ===================================

void voter::Edit()
{
      cout<<"What is the voters new Party: ";
      cin>>party;

}


// =========================== Display List of Voters  =============================

void voter::print(int label)
{
      cout << setw(3)
             << label            << setw(10)
           << idnumber      << setw(13)
             << lastname      << setw(8)  
             << firstname      << setw(9)
             << party            << setw(10)
             << birthyear      << setw(8)
             << currentage  << setw(8)
             << endl;
}


// =========================== Save to File on Disk ================================

void voter::disksave(ofstream& outfile)
{
outfile  << setw(6)  << idnumber
             << setw(14) << lastname  
             << setw(12) << firstname
             << setw(12) << party
             << setw(12) << birthyear
             << setw(12) << currentage  
             << setw(12)
         << endl;
}


// =========================== Destructor Argument  ================================

voter::~voter()
{

}



// Prototype Declaration

int  DisplayMenu(int);
void AddVoter(voter voterlist[], int&);
void EditVoter(voter voterlist[], int);
void PrintReport( voter voterlist[], int);
void SaveFile(voter voterlist[], ofstream&, int);
void SaveReport(voter voterlist[], ofstream&, int);
void GetData( voter voterlist[], int&, ifstream&, int&);
void DeleteVoter(voter voterlist[], int& size);


// Beginning of Program
void main()
{
      //Variable declaration
      const int arraysize = 100;
              int size      = arraysize;       
               int error     = 0;
              int choice    = 0;
             

      //Array declaration
      voter voterlist[arraysize];

      //Read and write declaration
      ifstream infile;
      ofstream outfile;

      //Calling funtion to get data to build array
      GetData (voterlist, error, infile, size);

      //
      while (choice <=6)
      {
      choice = DisplayMenu(choice);
      if (choice == 1)
      {
                  PrintReport(voterlist, size);
                  getche();
      }
      else if
         (choice == 2)
                  SaveReport(voterlist, outfile, size);
      else if
         (choice == 3)
                  AddVoter(voterlist, size);
      else if
         (choice == 4)
                  EditVoter(voterlist, size);
      else if
         (choice == 5)
                  SaveFile(voterlist, outfile, size);
            else if
         (choice == 6)
                  DeleteVoter(voterlist, size);
      }
            cls();
            cout << "Thanks for using program"
                   << endl;
            getche();

}
// End of program



int DisplayMenu(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] Save Report to Disk                        ";
      cout << setw(25) << "\n   [3] Add New Voter to List                      ";
      cout << setw(25) << "\n   [4] Change Party of Voter                      ";
      cout << setw(25) << "\n   [5] Make Backup File                           ";
      cout << setw(25) << "\n   [6] Delete Voter                               ";
      cout << setw(25) << "\n   [7] Exit Program                             \n";
      cout << setw(25) << "\n ============================================== \n"  
             << endl;
      
      cout << setw(22) << "Enter Selection >  ";
      cin  >> choice;

      return choice;

}


void GetData( voter voterlist[], int& error, ifstream& infile, int& size)
{
      int            age,
                  idnumber,
                  birthyear,
                  currentage  = 0,
                  numvoters   = 0;

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

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');
      // party = toupper(party);
      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 = error + 1;
            }
            else
            error = error + 1;
            }
            else
            error = error + 1;

      if (infile.fail())
      break;
      size = numvoters;
}
infile.close();
      
}



void AddVoter(voter voterlist[], int& size)
{
      cls();
      size++;
      voterlist[size-1].Add();
}



void EditVoter(voter voterlist[], int size)
{
      int choice;
      PrintReport(voterlist, size);
      
      cout<<"Which voter do you wish to edit: ";
      cin>>choice;
      choice--;

      voterlist[choice].Edit();
}      



void PrintReport(voter voterlist[], int size)
{
      cls();
      int label = 1;

      cout << "Report for: Data.txt"
            << endl
             << endl;

      cout << "Label"                << setw(10)
             << "Voter Id"   << setw(11)
             << "Last Name"  << setw(12)
             << "First Name" << setw(7)
             << "Party"             << setw(11)
             << "Birthyear"  << setw(5)
             << "Age"                  
             <<       endl;

      cout << "====="           << setw(10)
             << "========"   << setw(11)
             << "========="  << setw(12)
             << "==========" << setw(7)
             << "====="      << setw(11)
             << "========="  << setw(5)
             << "==="
             <<  endl;

      for (int n = 0;n < size  ;n++)
      {
            voterlist[n].print(label);
            
            label++;
      }
      cout << endl;
}



void SaveFile(voter voterlist[], ofstream& outfile, int size)
{
      cls();
      OpenOutput(outfile);

      for (int n = 0;n < size ;n++)
      {
            voterlist[n].disksave(outfile);
      }
      outfile.close();
}




void SaveReport(voter voterlist[], ofstream& outfile, int size)
{
      cls();
      OpenOutput(outfile);
      

      outfile << "Report for: Data.txt"
                << endl
                << endl;
            
      outfile << "Id Number"   << setw(11)
                  << "Last Name"   << setw(15)
                  << "First Name"  << setw(12)
                  << "Party Id"    << setw(12)
                  << "Bith Year"   <<  setw(13)
                  << "Current Age" << endl;

      outfile << "========="   << setw(11)
                  << "========="   << setw(15)
                  << "=========="  << setw(12)
                  << "========"    << setw(12)
                  << "=========="  << setw(13)
                  << "===========" << endl;

      for (int n = 0;n < size ;n++)
      {
            voterlist[n].disksave(outfile);
      }
      outfile.close();
}



void DeleteVoter(voter voterlist[], int& size)
{
      int choice;
      PrintReport(voterlist, size);
      
      cout<<"Which voter do you wish to delete: ";
      cin>>choice;

      
   for (int i=choice; i< size; i++) {
       voterlist[i] = voterlist[i+1];
   }
   size--;            
   return;

}      
rbran74Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

efnCommented:
I was unable to reproduce your result.  I took all your hundreds of lines of code, removed the file interface so it would compile, and added initialization of size to zero in main.  Then I was able to add three records and when I deleted a record, one other than the last one disappeared.

There was some inconsistency in that I told it to delete record 1 and it deleted the one displayed with the label 2.  This is because the program displays the records with 1-based labels, but uses the input specification of which record to delete as a zero-based subscript.  Possibly, this is what is confusing you.  Or there may be a problem in the file input/output routines that weren't used in my test.

--efn
dhyaneshCommented:
Hi

Change your delete voter function as:

void DeleteVoter(voter voterlist[], int& size)
{
    int choice;
    PrintReport(voterlist, size);
   
     cout<<"Which voter do you wish to delete: ";
    cin>>choice;

     if (choice <= size)
     {
           for (int i=choice-1; i< size-1; i++) {               //i start from choice - 1 and not choice
               voterlist[i] = voterlist[i+1];
            size--;            
      }
      else
          cout<<"Error voter not found";
  }
  return;
}  

This is because all your labels start from 1 but the index of voterlist array starts from 0. Also the for loop has to run until size-1 because you are copying the last record to the second last record in last run of loop. Hence you do not process for last record.

Also it is good to check if the choice if within range for error handling otherwise size will decrease without decrease in voter.

Dhyanesh

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AxterCommented:
>>what am I doing wrong here

One of the things wrong here is that you're using non-standard header files.
#include<iostream.h>
#include<iomanip.h>
#include<fstream.h>

The above files are not part of the C++ standard.
That means your compiler can yield one result, and an expert's compiler can yield another result.

I highly recommend changing the code to use header files that are part of the C++ standard.
Example:
#include<iostream>
#include<fstream>

Use the extensionless header files.

You can add "using namespace std" to avoid having to prefix all your code with std::
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.