Solved

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

Posted on 2003-11-30
3
243 Views
Last Modified: 2010-04-02
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;

}      
0
Comment
Question by:rbran74
3 Comments
 
LVL 15

Expert Comment

by:efn
ID: 9848391
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
0
 
LVL 4

Accepted Solution

by:
dhyanesh earned 125 total points
ID: 9848474
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
0
 
LVL 30

Expert Comment

by:Axter
ID: 9849335
>>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::
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
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.

762 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

20 Experts available now in Live!

Get 1:1 Help Now