still frustrated

Started by
12 comments, last by AngleWyrm 13 years, 5 months ago
This is the 3rd time that I have wrote this program. This time I finally got it to compile with no errors. I researched arrays and pointers as instructed and I thought I really understood it. So I went back and re-wrote the entire thing. Now it will run the program but terminates and I cannot figure out where the error is. Also I prompt the user to input the canidates name followed by the number of votes recieved, but I dont think this is giving me the results I desire. I have 5 canidates and 5 correlating number of votes, how do get it to where the user inputs canidate1 >> vote1 (enter) canidate2 >> vote2; etc...

//
// Author: Lauren Settle
//
//Program: Local Election
//
// This program prompts the user to input the last names of 5 canidates in a local election and the number of votes they recieved.
// The program then outputs the canidates name, the number of votes recieved, the percent of total votes, and output the winner.
//

# include <iostream>
# include <iomanip>
# include <string>

using namespace std;

void initialize (const int noOfCanidates, double percentVotes[], double noOfVotes[]); // function prototype to initialize variables
void sumVotes (const int noOfCanidates, double totalVotes, double noOfVotes[]); // function prototype to calculate the total number of votes
void percentage (const int noOfCanidates, double percentVotes[], double totalVotes, double noOfVotes[]); // function prototype to calculate the percent of total votes each canidate recieved
void winner (const int noOfCanidates, int maxVotes, double noOfVotes[], string canidatesName[]); // function prototype to calculate who had the highest number of votes
void printResults (const int noOfCanidates, double noOfVotes[], string canidatesName[], double percentVotes[]); // function prototype to print results

int main()
{
const int noOfCanidates = 5;
int i;
int maxVotes = 0;
double totalVotes = 0;
string canidatesName[noOfCanidates]; //array to store canidates last names
double noOfVotes[noOfCanidates]; // array to store how many votes each canidate recieved
double percentVotes[noOfCanidates]; // array to store the percent of votes each canidate recieved

initialize (noOfCanidates, percentVotes, noOfVotes);

cout << " Enter the last name of the canidate followed by the number of votes recieved. " << endl;

// this is the section that I am not happy with, I do not think that I formatted it correctly to give
// me the desired results.
while (i < noOfCanidates)
{
i++;
cin >> canidatesName[noOfCanidates] >> noOfVotes[noOfCanidates];
}

sumVotes (noOfCanidates, totalVotes, noOfVotes);
percentage (noOfCanidates, percentVotes, totalVotes, noOfVotes);
winner (noOfCanidates, maxVotes, noOfVotes, canidatesName);
printResults (noOfCanidates, noOfVotes, canidatesName, percentVotes);

cout << " The Winner of the Election is " << canidatesName[maxVotes] << " . " << endl;

/* Scaffolding code for testing purposes */
cin.ignore(256, '\n');
cout << "Press ENTER to continue..." << endl;
cin.get();
/* End Scaffolding */
return 0;

}

void initialize (const int noOfCanidates, double percentVotes[], double noOfVotes[])
{
int i, j;

for (i = 0; i < noOfCanidates; i++)
noOfVotes = 0.0;

for (j = 0; j < noOfCanidates; j++)
percentVotes[j] = 0.0;
}

void sumVotes (const int noOfCanidates, double totalVotes, double noOfVotes[])
{
int i;
double sum = 0;

for (i = 0; i < noOfCanidates; i++)
totalVotes = sum + noOfVotes;
}

void percentage (const int noOfCanidates, double percentVotes[], double totalVotes, double noOfVotes[])
{
int i;

for (i = 0; i < noOfCanidates; i++)
percentVotes = (noOfVotes / totalVotes) * 100;
}

void winner (const int noOfCanidates, int maxVotes, double noOfVotes[], string canidatesName[])
{
int i;

for (i = 1; i < noOfCanidates; i++)
if (maxVotes < noOfVotes)
maxVotes = i;
}

void printResults (const int noOfCanidates, double noOfVotes[], string canidatesName[], double percentVotes[])
{
int i;

cout << " ------------- Election Results ------------- " << endl << endl;
cout << " Canidates Name------Votes Recieved-------% Of Votes------" << endl << endl;

for (i = 0; i < noOfCanidates; i++)
{
cout << left;
cout << setw(9) << canidatesName << " ";
cout << right;
cout << setw(8) << noOfVotes << " ";
cout << setw(6) << percentVotes << " ";
cout << endl << endl;
}
}

Advertisement
Hey Lauren,

It looks like, in the problem point, you're using i before its been initialized.

Edit:
As another note, you may want to use a for loop for this kind of loop:

for(int i = 0; i < noOfCandidates; i++) { ...}


This has the variable initialization, terminating condition, and increment all in one place.


Also this line in the loop is a problem:

cin >> canidatesName[noOfCanidates] >> noOfVotes[noOfCanidates];


I think what you meant to do is to fill the array with the input data. However, each iteration will write to the same spot in the array (spot number 5). To add to the problems, this spot is outside the valid length of the array.

When posting source code, please use the [source][/source] tags; as they preserve your formatting. Anyways:

int i;// .// .// .// this is the section that I am not happy with, I do not think that I formatted it correctly to give// me the desired results.while (i < noOfCanidates){    i++;    cin >> canidatesName[noOfCanidates] >> noOfVotes[noOfCanidates];}


There are a couple of problems with this code:
  1. 'i' needs to be initialized to some value before entering the loop.
  2. Unless your assignment requires you to use a 'while' loop, I would recommend using a 'for' loop instead, to be consistent with the rest of your code.
  3. Remember that arrays in C++ are 0-index based, this means that for N elements in an array you can access those elements via from 0 (the first element) to N-1 (the last element). Look closely in your code, as it seems that the code repeatedly asks the user for the Nth element (an invalid element in the array) of canidatesName and noOfVotes.


int main() {    // ...    int maxVotes = 0;    winner (noOfCanidates, maxVotes, noOfVotes, canidatesName);}// ...void winner (const int noOfCanidates, int maxVotes, double noOfVotes[], string canidatesName[]){    int i;    for (i = 1; i < noOfCanidates; i++)        if (maxVotes < noOfVotes)            maxVotes = i;} 

The winner function doesn't modify the maxVotes variable in main, because parameters are passed by value; the parameters passed in are copied to the function being called. In order to allow this function do modify variables, you must pass the parameter by reference, or have winner return an integer. (And a small bug, in all of your loops, 'i' starts at 0, why does this function have 'i' start at 1? Is this intentional?)

HTH.
void sumVotes (const int noOfCanidates, double totalVotes, double noOfVotes[]){	int i;        double sum = 0;	for (i = 0; i < noOfCanidates; i++)	{		totalVotes = sum + noOfVotes;	}}


You appear to be using this function to sum up the number of total votes. Since you passed totalVotes by value, whatever you stick in totalVotes is not going to be returned to main(). You can fix this in two ways: You can add a return value, sum it up in a variable in sumVotes (like sum), and then return it from the function using the return statement, or you can set totalVotes to be a reference, in which case it will pass a reference to the totalVote variable that you gave the function in main.

Also, I'll note that your summation code here is incorrect. I think if you'll take a look at it you'll be able to figure out why fairly easily.

Edit:

By the way, can I ask if your school is using Visual Studio 6.0? I noticed you're doing this with your for-loops:

	int i;	for (i = 1; i < noOfCanidates; i++)	{           ...        }


Its not necessary to declare the int before the loop. You can do this:

for(int i = 1; i < noOfCanidates; i++){...}


A lot of old text books will do what you did because Visual Studio 6.0 (a very old version) had problems with the way the variables in the for-loop worked. If you're not using Visual Studio, its better to use the latter format.

Another Edit:

To also add to __fastcall's discussion of your winner function, it doesn't appear to be doing what you intend it to do. It seems you're conflating the number of votes with the index position of the person with the most votes.

[Edited by - Rycross on October 23, 2010 12:25:51 PM]
thanks. I initialized i. and I fixed the functions that needed return values. but I am still having trouble with filling the arrays with user inputed data.

cout << " Enter the last name of the canidate followed by the number of votes recieved. Seperate them with a space. " << endl;

// this is the section that I am not happy with, I do not think that I formatted it correctly to give
// me the desired results.

for (i = 0; i < noOfCanidates; i++)
{
cin >> i;
cin >> canidatesName >> noOfVotes;
i++;
}
Well why are you not happy with it?
You're almost there.

Quote:Original post by borogirl09
    // this is the section that I am not happy with, I do not think that I formatted it correctly to give    // me the desired results.                for (i = 0; i < noOfCanidates; i++)        {            cin >> i;              cin >> canidatesName >> noOfVotes;              i++;        }



How many times is 'i' incremented per loop? Do you need to know which specific candidate you're entering information for? (In other words, do you really need 'cin >> i;'?)
Quote:Original post by borogirl09
for (i = 0; i < noOfCanidates; i++){  cin >> i;  cin >> canidatesName >> noOfVotes;  i++;}
What this is doing is getting the data from the keyboard and overwriting i with whatever the user entered. You don't want to overwrite i because i is used to tell the computer what candidate you are on. The user doesn't need or want to keep track of that information. Worst of all, if the user enters in a value for i that is greater than noOfCandidates (or negative) the program will try to access invalid data from candidatesName and noOfVotes.

After that you are correctly getting the candidatesName and noOfVotes for the current candidate.

But after that you are updating i again which is bad because the for loop is already updating i for you at the end of every loop. Double dipping is frowned upon at parties but it is worse when you do it in a for loop. At least in this case.

In addition to what I wrote above I will give you this hint: you can fix that loop by deleting 2 specific lines and keeping everything else identical.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Well I deleted the lines that I didn't need which left me with this. When I run the program it prompts me to input the canidates name followed by the votes seperated by a space. So for instance I enter haynes 13 and press enter the program closes. It does not allow me to input all 5 canidates, nor does it seem to be storing it.
UGHHHHHHHHHHHH!!!!!


for (i = 0; i < noOfCanidates; i++)
{
cin >> canidatesName >> noOfVotes;
}
Did you read the answer I gave you in the last thread you made?

Did you enter "haynes 13" on a line and hit enter?
I think you'd have to enter "haynes" then press enter, and then "13" then press enter.

This topic is closed to new replies.

Advertisement