What am I doing wrong?

So I believe I messed up somewhere where I asked the user to input the last name of a person. I can input 1 name, and then it spits out the rest of the words. Can anyone help me?

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX = 5;

char names[MAX];
int votes[MAX];
float percent[MAX];
int numberCandidates = 0;
int *candVotes;
int totalVotes;
int winner;
int winnerVotes;
void get_input();
void calculate_winner();
void show_output();

int main()
{
	get_input();
	calculate_winner();
	show_output();

	system("pause");
	return 0;
}

void get_input()
{
	cout << "Please enter number of candidates: ";
	cin >> numberCandidates;
	candVotes = new int[numberCandidates]; // Dynamic Array


	totalVotes = 0;
	for (int i = 0; i <= numberCandidates - 1; i++)
	{
		cout << "Enter Last Name of Candidate #" << i + 1 << ": ";
		cin >> names[i];
		cout << "Enter Number of Votes received: ";
		cin >> candVotes[i];
		totalVotes += candVotes[i];
	}
}


void calculate_winner()
{
	winner = 0;
	winnerVotes = votes[0];


	for (int i = 1; i<MAX; i++)
		if (winnerVotes < votes[i])
		{
			winner = i;
			winnerVotes = votes[i];
		}
}

void show_output()
{
	cout << endl << endl << "Candidate"
		<< "       Votes Rec" << "   % Of Total Votes" << endl;
	for (int i = 0; i <MAX; i++)
		cout << setiosflags(ios::left) << setw(20) << names[i]
		<< setw(12) << votes[i]
		<< setw(10) << ((float)votes[i] / (float)totalVotes)*100.0 << "%"
		<< endl;
	cout << endl;

	cout << "Winner of the election is" << names[winner] << endl << endl << endl;
}
Not really answering your question, but you do a lot of things in a way that isn't particularly efficient. variables of the same type can be stacked into the same statement, such as int i, j = 0, k;. A for loop iterator is best written with the end condition as i < numberCandidates as opposed to i <= numberCandidates - 1. As for your question, your names variable seems to be improperly implemented. Assuming you wanted an array of strings, you should either #include string.h and make it a string array, or if you can't use string, make it char* names[MAX];. I'm pretty sure you assign a char* with a string literal.
Or use 2D array, like names[howmuchcandidates][maxlettereachname]
Last edited on
Topic archived. No new replies allowed.