I have a file that I am supposed to retrieve names from and make a list of it. There is something wrong with the candidates vector because when I try to call it for the output I get a segmentation fault.
int main()
{
string name;
vector<string> candidates;
vector<int> votes;
vector<double> percents;
//setup for random number generation
srand(time(0));
//rand % n gives you random numbers between 0 and n-1 (inclusive)
//generating random number of votes
for (int i=0; i<=16; i++)
{
int x = rand()%9000;
while (x<1500)
{
x = rand()%9000;
if (x>=1500)
{
votes.push_back(x);
}
}
votes.push_back(x);
i;
//cout << votes[i] << "\n";
}
//vote percent
double sum = accumulate( votes.begin(), votes.end(), 0.0);
for (int i=0; i<=16; i++)
{
int x = (votes[i]/sum)*100;
percents.push_back(x);
//cout << percents[i] << "\n";
}
//creating inputfile object
ifstream inputfile;
//linking the object to a text file
inputfile.open("candidates.txt");
//determining if the file was properly opened
if (!inputfile)
{
cout << "not opened" << endl;
return -1;
}
//reading from the file into a variable
//determining if there is anything left to read from the file
while (inputfile >> name)
{
candidates.push_back(name);
}
cout << "Candidate" << setw(10) << right << "Votes" << setw(13) << right << "Percents";
for (int i=0; i<=16; i++)
{
cout << candidates[i] << setw(10) << right << votes[i] << setw(13) << right << percents[i] << "%\n";
}
}
How many candidates are there in the file? Line 60 implies (at least) 17.
I suggest that you read the candidates' names first, and work with candidates.size(), not the magic number 16. (In a British election that is a huge number!).
Remove lines 19-22 or you will have some vote-rigging!