473,246 Members | 1,538 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

C++ Outfile Voting Election Candidate Problem

First, thanks in advance to those who is willing to help me. Second, I'm a total noob at C++ programming, so the code i'm posting might be completely wrong nd needs to be redone. Anyways, here's the problem i'm faced with, word for word from the C++ book: A data file called votelist contains a list of candidates voted for by each student. Any line of the file may contains 5 numbers, with each number representing a candidate. Write a program that reads the file and prints a list of the total votes received by each candidate. Also, print the five highest vote getters from highest to lowest. OK, so basically, the way i take it is that i make a random file called "votelist" and put 5 numbers on each line. Then, I read from that file and tally up how many times each number appears. Then, from those numbers, order the 5 numbers that appear the most from highest to lowest. And just to clear things up, each candidate is assigned a number, 1-15, and each student votes for 5 people, thus the five numbers per line. problem is, i don't know to tally the votes froma textfile, much less order them. Here's my code so far. If you have any idea or insight, please help. Not trying to hurry anyone, but this is due in 2 days, on friday. Thanks.

Expand|Select|Wrap|Line Numbers
  1. #include <iomanip.h>
  2. #include <iostream.h>
  3. #include <fstream.h>
  5. int main()
  6. {
  7.     int vote, one, two, three, four, five;
  8.     char a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
  9.     ofstream out_file;
  10.     ifstream in_file;
  12.     in_file.open("votelist");
  14.     cout << "\t\t\tVotes for the 15 Candidates" << endl;
  15.     cout << "C1  " << "C2  " << "C3  " << "C4  " << "C5  " << "C  " << "C7  " << "C8  " << "C9  " << "C10  " << "C11  " << "C12  " << "C13  " << "C14  " << "C15"<< endl;
  16.     cout << endl;
  19.     do
  20.     {
  21.         in_file >> vote >> vote >> vote >> vote >> vote;
  23.         if(vote = 'a')
  24.         {
  25.             a++;
  26.         }
  28.         else if(vote = 'b')
  29.         {
  30.             b++;
  31.         }
  33.         else if(vote = 'c')
  34.         {
  35.             c++;
  36.         }
  38.         else if(vote = 'd')
  39.         {
  40.             d++;
  41.         }
  43.         else if(vote = 'e')
  44.         {
  45.             e++;
  46.         }
  48.         else if(vote = 'f')
  49.         {
  50.             f++;
  51.         }
  53.         else if(vote = 'g')
  54.         {
  55.             g++;
  56.         }
  58.         else if(vote = 'h')
  59.         {
  60.             h++;
  61.         }
  63.         else if(vote = 'i')
  64.         {
  65.             i++;
  66.         }
  68.         else if(vote = 'j')
  69.         {
  70.             j++;
  71.         }
  73.         else if(vote = 'k')
  74.         {
  75.             k++;
  76.         }
  78.         else if(vote = 'l')
  79.         {
  80.             l++;
  81.         }
  83.         else if(vote = 'm')
  84.         {
  85.             m++;
  86.         }
  88.         else if(vote = 'n')
  89.         {
  90.             n++;
  91.         }
  93.         else if(vote = 'o')
  94.         {
  95.             o++;
  96.         }
  97.     } while(! in_file.fail() || ! in_file.eof());
  98.     in_file.close();
  100.     cout << a << " " << b << " " << c << " "  << d << " " << e << " " << f << " " << g << " " << h << " " << i << " " << j << " " << k << " " << l << " " << m << " " << n << " " << o << endl;
  101.     cout << "The top five candidates are:" << endl;
  102.     cout << one << endl;
  103.     cout << two << endl;
  104.     cout << three << endl;
  105.     cout << four << endl;
  106.     cout << five << endl; 
  107.     return 0;
  108. }
Feb 28 '08 #1
5 6172
3,652 Expert 2GB
Let's look at a few problem points in your program:

1) infile >> vote >> vote >> vote...;

This is going to read the first value from infile into vote. It's then going to read the second value into vote, before vote is ever used. The first value is now gone forever, before it's been tallied. It then reads the third value, clobbering the second value. This goes on until the 5th value, so you really are only considering every 5th value. You can just have infile >> vote;, which will read a value from infile into vote. Then the loop executes, you calculate that value, and then read the next one in. Note than when you reach the end of the line and call infile >> vote, infile will look for the next value, regardless of whitespace. So it will automatically go to the next line.

2) if (vote == 'a') {...} else if (vote == 'b') {...} ...

This is a huge chunk of code than can be reduced dramatically by using a switch statement. In addition to looking a LOT better, it is actually faster to run in the end. Your switch statement would look like:

Expand|Select|Wrap|Line Numbers
  1. switch (vote) {
  2.    case 'a': a++; break;
  3.    case 'b': b++; break;
  4.    // And so on, through:
  5.    case 'o': o++; break;
  6.    default: // vote didn't correspond with a candidate
  7.       cout << "Error!  " << vote << " is not a valid candidate." << endl;
  8. }
In fact, you can simplify this even more: It will be very easy to use an array to store these fifteen values. Let's say you have

int candidates[15] = {0}; // initializes every element to 0 (0 votes initially)

Then you can simply say


If vote is 'a', then 'a'-'a' is 0, and the 1st element of candidates is updated. If vote is 'b', then 'b'-'a' is 1, and the 2nd value is updated, etc.

3) Your ordering is going to be very difficult if you are using 15 different integers. (You will have to find the maximum of 15 values, then the maximum of 14 value, etc. etc.). It will be easier to get the top 5 values with the array, since you can sort the array using one of many simple sorting algorithms. If you need to get the letter as well, you may want to use a struct to store the candidate name and the vote total. This might be too complicated for your assignment, though - ask your professor/teacher.
Feb 28 '08 #2
Hi. WOW. first, thanks a million, your a god. So the in_file will just loop regardless of line issues, thats cool. The only problem is, we technically havent learned arrays yet so we cant use that. I'll implement your suggestions and see if i can get it to work and see if my teacher is cool with it. I'll post soon. Thanks again.
Feb 28 '08 #3
Hi, Yea, so i dont know how to use arrays and im not allowed to use it. Do you, or does anyone else know of any way to order the top five candidates from highest to lowest? Like, how do you find the 5 people with the highest votes? Thanks again. Please help
Feb 28 '08 #4
671 Expert 512MB
Your book is outdated. Dead giveaways: <iomanip.h>, <iostream.h>, etc.. The 98 (yes, that's a decade ago) revision of C++ changed how standard headers work. iomanip, iostream, and the company are part of the C++ standard library. Hence, the format for them is <iomanip>, <iostream>, and <fstream> . The ".h" gets dropped for them. Furthermore, they are within the std namespace. For now, you will not have to worry about the implications of namespaces.

So you can get away with a using namespace std; right after the includes.

Oh, and if it's part of the C library, like math.h, in C++ it's <cmath>. It's a standard header, so no .h. But it's a C header, so prefix it with "c". If you're wondering where we come up with these header names, you can check with Google. cplusplus.com and cppreference.com are easy to find and do a decent job of summarizing the library.

The only problem is, we technically havent learned arrays yet so we cant use that.
Not such a fun assignment then...In any case, if you know switch statements, then that is what you were expected to use.

Do you, or does anyone else know of any way to order the top five candidates from highest to lowest? Like, how do you find the 5 people with the highest votes?
The category of algorithms that "order" items are called sorting algorithms. This may be a great time for you to learn something like bubble sort or insertion sort, which are simplistic but provide acceptable performance at very small numbers of items.
Feb 28 '08 #5
Hi. Thanks for the reply. I settled the switch statement problem. Now can you elaborate a little on the sorting part of this problem please. Like, what are bubble sort or insertion sort? I'll google it, but see, for me, i usually need to see the code implemented to understand it. C++ Lingo is very confusing to me and i can't understand it. A sample code is much more helpful. And, also, regarding this book being old, you are right on. In fact, the software we're using is old as heck too, visual c++ 6.0. There's like C++ version 9.0 out now. I don't know why my school is so far behind, since we just got like awesome new computers with flat screen monitors that cost like $1500 each. Anyways, i regret taking the class, as the book sucks, the software is also outdated, and my teacher can't teach. I'm like a visual lerner, and when he goes into deep c++ lingo and stuff, i get completely lost, which is why i have come here for help. Thanks again.
Feb 29 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

by: PiedmontBiz | last post by:
Listening to National Public Radio while reading comp.lang.python. What a life! I just heard a piece on NPR about the security failures of an electronic voting system being developed. I know a...
by: Marco Bubke | last post by:
Hi I have read some mail on the dev mailing list about PEP 318 and find the new Syntax really ugly. def foo(x, y): pass I call this foo(1, 2), this isn't really intuitive to me! Also I...
by: solartimba | last post by:
Hi, I am in another country, and I need to finish a program. But I do not have any reference books. Can you tell me how to print this to a file without ending the stream with an endl. Stated...
by: sitpost | last post by:
Only days before the election, a few key ‘battleground-states' esp. OHIO are barraged with political ads; which are increasingly "canceling each other out!" Talk about the "fog of politics!" A...
by: AES | last post by:
Can anyone point to software or HTML code (preferably shareware or modest cost, preferably Mac or PC based) that would permit a small organization to carry out a simple election with online voting...
by: Eric | last post by:
I thought it might be fun to run a simple vote to discover the most preferred spacing style for a simple if statement with a single, simple boolean test. By my count, there are 32 possible...
by: Marek Zawadzki | last post by:
Hi all. Is it possible to implement an accurate voting mechanism (think digg.com) that does not require users to sign in before voting? I think for many people registering is pain and thus...
by: varusnyc | last post by:
Hello, Im having really hard time writing an Employee Payroll program that uses functions to read data from file then send all data to another file. I managed to construct some pieces of the code,...
by: rhitz1218 | last post by:
All: I'm trying to create a log file. I now I can be able to do that by doing the following: FILE *outfile; outfile = fopen("log.txt", "w"); fprintf("This is the text");
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.