i have initialized the elements of the array by reading the strings from a file, however when I call the sort function, either the program crashes or it just outputs NULL. What could be a more efficient way to store data from a file?
the file that I have opened contains the following text:
"
ppp zaeem na2 lun
pti farea na1 balla
"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <Conio.h>
#include <cstdlib>
#include <string>
#include <string.h>
#include <cstring>
#include <fstream>
using namespace std;
class candidate
{
public:
string party;
string name;
string constituency;
string symbol;
candidate()
{
party = "";
name = "";
constituency = "";
symbol = "";
}
};
candidate *candi = new candidate[3];
int size = 0;
void read_into_array()
{
int i = 0;
string name, party, consti, symb;
ifstream a("new.txt");
if (!a)
cout << "file not found." << endl;
else
{
a >> party >> name >> consti >> symb;
while (!a.eof())
{
candi[i].party = party;
candi[i].name = name;
candi[i].constituency = consti;
candi[i].symbol = symb;
a >> party >> name >> consti >> symb;
size++;
i++;
}
a.close();
}
}
class voter
{
public:
void show_all_candidates()
{
for (int i = 0; i < size; i++)
{
cout << "Candidate's Name: " << candi[i].name << endl;
cout << "Candidate's Constituency: " << candi[i].constituency << endl;
cout << "Candidate's Party'" << candi[i].party << endl;
cout << "Party Symbol: " << candi[i].symbol << endl;
}
}
void sort_by_name()
{
for (int i = 1; i < size; i++)
{
for (int j = 1; j <size-i; j++)
{
string temp=" ";
if (candi[j].name > candi[j + 1].name)
{
temp=candi[j].name;
candi[j].name = candi[j + 1].name;
candi[j + 1].name = temp;
temp=candi[j].constituency;
candi[j].constituency = candi[j + 1].constituency;
candi[j + 1].constituency = temp;
temp=candi[j].party;
candi[j].party = candi[j + 1].party;
candi[j + 1].party = temp;
temp=candi[j].symbol;
candi[j].symbol = candi[j + 1].symbol;
candi[j + 1].symbol = temp;
}
}
}
}
};
int main()
{
voter obj_voter;
read_into_array();
obj_voter.sort_by_name();
obj_voter.show_all_candidates();
// obj_voter.sort_by_name();
}