"Voting machine" in C++ using Geany [Linux]

Hello, people! I need help with only one thing I need for this program to work perfectly.

The "voting machine" can input all the votes (apparently) and the loop goes on nicely except I don't know how make it STOP! I'm using "switch" combined with "while".

The source-code:

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
#include <iostream>
#include <curses.h>

int input,cand1,cand2,nulo,total,g,vg,pc_1,pc_2,pc_n;
int main(int argc, char **argv)
{
cand1=0,cand2=0,nulo=0,pc_1=0,pc_2=0,pc_n=0; do
{
printf("\nSEGUNDO TURNO\n\n");
printf("1. Candidato 1\n");
printf("2. Candidato 2\n");
printf("3. Nulo\n");
printf("\nSeleção: ");
scanf("%i",&input);

switch ( input )
{
case 1: cand1++;    
break;
case 2: cand2++;
break;
case 3: nulo++;
break;
default: printf("Erro, digito invalido! Digite novamente\n");
break;
}
}
while (input);
total=cand1+cand2+nulo;
g=1; vg=cand1;
if (cand2 > vg) {g = 2; vg = cand2;}
if (nulo > vg) {g = 3; vg = nulo;}
printf("\nNumero do Vencedor = %i", g);
printf("Total de Eleitores Validos = %i", total);
printf("Numero de Votos por Candidato\n");
printf("Cand1 = %i", cand1);
printf("Cand2 = %i", cand2);
printf("Nulos = %i", nulo);
printf("Percentual de Votos\n");
pc_1=cand1*100/total;
pc_2=cand2*100/total;
pc_n=nulo*100/total;
printf("perc cand1 = %i", pc_1);
printf("perc cand2 = %i", pc_2);
printf("perc nulo = %i", pc_n);
return 0;
}
Last edited on
What happens when you type zero? I would use zero as the condition to break out of your "do-while" loop.
It stops when I type zero.

How could I make it "automatic"? After a pre-determined number of inputs?
Last edited on
What do you mean by automatic?
Program the loop to stop after X inputs.
Have a look at using a for loop instead of do..while. for loops are typically used in situations where you'd like to repeat a specific number of times, whereas the 'while' keyword is intended for repeating an arbritrary number of times until a particular condition is met.


(You could also re-work your 'while' loop to use a condition involving a counter variable which increments at the end of each iteration, but that would just be imitating a 'for' loop).
I'll study for loops more and modify the code. Thanks a lot!
Topic archived. No new replies allowed.