Beginner code completed question?

closed account (zTUSz8AR)

Hi everyone this is what I have so far for the following problem so far its working correctly I just want to know how to move the numbers to display under the % of total votes? I also want to add a total of all the votes?











Write a program that
allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate.
The program should then output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate.
Your program should also output the winner of the election.
This program must be done using parallel arrays to store the name and number of votes for each candidate.
The number must be formatted appropriately as shown in the sample output below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

#include <string>
#include <iostream> 
#include <iomanip> 
using namespace std;
int main()
{
	string names[5];
	int votes[5];

	
	int winner;
	int total = 0;
	string winner_name;

	cout << "Enter candidate's name and the votes received by the candidate." << endl;

	
	
	for (int i = 0; i<5; i++)
	{

		
		cin >> names[i];
		cin >> votes[i];

		total += votes[i];
	}

	winner = votes[0];

	//This for loop will decides the winner based on the votes  
	for (int j = 0; j<5; j++)
	{
		if (votes[j]>winner)
		{
			winner = votes[j];
			winner_name = names[j];
		}

	}
	std::cout << std::setprecision(2) << std::fixed;


	cout << "Candidate\tVotes Received\t% of Total Votes" << endl;
	for (int i = 0; i<5; i++)
	{
		cout << setw(10) << names[i] << "\t" << votes[i] << "\t"<< ((double)votes[i] / total) * 100 << endl;
	}
	cout << "The Winner of the Election is " << winner_name << endl;

	system("PAUSE");
	return 0;
}
Hey Elanor,
You have to setw() for each displayed string, making sure the value is big enough. Also align the output. See code below.

1
2
3
4
5
cout << left << setw(20) << "Candidate" << setw(20) << "Votes Received" << setw(20)  << "% of Total Votes" << endl;
	for (int i = 0; i<1; i++)
	{
		cout << left << setw(20) << names[i] << setw(20) << votes[i] << setw(20) << ((double)votes[i] / total) * 100 << endl;
	}
Hello elanor,

In line 48 you can use a combination of std::setfill(' ') and std::setw(n) to space out what you print. std::setfill() will fill in the unused portion of the std::setw(n) width.

http://www.cplusplus.com/reference/iomanip/setfill/?kw=setfill

Hope that helps,

Andy
Topic archived. No new replies allowed.