Sunday, July 12, 2009

I need some help with a C++ program?

Hey I keep getting errors in this program and im not sure how to fix them, the program is supposed to tally up votes and print out winners in 6 different races. I'll post the program first and then my question:








#include%26lt;iostream%26gt;


#include%26lt;fstream%26gt;


using namespace std;


void tally(int%26amp;,int%26amp;,int%26amp;,int%26amp;,int%26amp;,int%26amp;,int%26amp;...


void print(int, int, int, int);





int main() {





cout%26lt;%26lt;"CS-114 Ballot Counter"%26lt;%26lt;endl%26lt;%26lt;endl;








cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Here's the race for the Presidency:"%26lt;%26lt;endl;


print(1, 2, p1, p2);





cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Here's the race for the Vice Presidency:"%26lt;%26lt;endl;


print(3, 4, vp1, vp2);





cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Here's the race for the Secretary:"%26lt;%26lt;endl;


print(5, 6, s1, s2);





cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Here's the race for the Treasurer:"%26lt;%26lt;endl;


print(7, 8, t1, t2);





cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Here's the race for the Judge:"%26lt;%26lt;endl;


print(9, 10, j1, j2);





cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Here's the race for the Senator:"%26lt;%26lt;endl;


print(11, 12, sen1, sen2);





}

I need some help with a C++ program?
Undeclared identifier means you're using a variable that you haven't declared yet, and the compiler doesn't know what it is since you haven't told it. You need to declare p1, p2, vp1, etc before you ask the computer to print them. So at the very top of your main(), you need this statement:





int p1, p2, vp1 .... sen1, sen2;





You probably need to initialize all of them to zero too before you start; otherwise they will contain garbage values.





Next, if your program really executes in that order, I think you're trying to print the results before you actually collect them, so you need to open ballot.txt and tally up the votes before you call print(1, 2, p1, p2) etc.





Also, you're getting voter %26gt;%26gt; vote before your while loop, then doing it again once you get inside the loop, so you're always going to miss the first vote, unless the first entry in ballot.txt is a dummy value. You should delete the first voter %26gt;%26gt; vote; statement. If the file's empty, you'll get an error there anyway.





Your big long if block should be a switch-case statement instead of a series of if's. I believe the syntax is like this:





switch(vote)


{


case 1: p1++; break;


case 2: p2++; break;


default: cerr %26lt;%26lt; "Invalid vote";


}


The default case is for when none of the other cases match. You currently have p1+=0 for that, which makes no sense. You should just do nothing, or at least output an error message.





Good luck with your program!

email cards

No comments:

Post a Comment