hello , i made a election program , here it is
#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <iomanip>
#include <fstream>
using std::ofstream;
using namespace std;
string users[4];
char choice2;
int votes[100] = {0};
int choice;
int totalVotes=0;
void votes1() {
cout<<"Voting! : "<<endl;
cout<<setw(21)<<left<<"(1) To vote " <<users[0]<<endl;
cout<<setw(21)<<left<<"(2) To vote " <<users[1]<<endl;
cout<<setw(21)<<left<<"(3) To vote " <<users[2]<<endl;
cout<<setw(21)<<left<<"(4) To vote " <<users[3]<<endl;
cin>>choice;
switch(choice) {
case 1:
votes[0]++;
break;
case 2:
votes[1]++;
break;
case 3:
votes[2]++;
break;
case 4:
votes[3]++;
break;
default:
cout<<"Incorect number... Exiting";
exit(1);
}
cout<<"Would you like to vote again? (y / n):"<<endl;
cin>>choice2;
if(choice2=='y') {
system("cls");
return votes1();
} else
{
system("cls");
cout<<setw(21)<<left<<"Users" <<"Votes \n"<<endl;
for(int c=0;c<4;c++) {
cout<<setw(21)<<left<<users[c]<<votes[c]<<endl;
}
cout<<left<<"-----------------------"<<endl;
for (int counter = 0; counter < 4; counter++)
{
totalVotes += votes[counter];
}
cout<<setw(21)<<left<<"Total Votes: "<<totalVotes<<endl;
}
}
int main()
{
cout<<"Insert 4 names:"<<endl;
for(int i=0;i<4;i++)
{
getline(cin, users[i]);
}
system("cls");
votes1();
ofstream outdata; // outdata is like cin
outdata.open("text.txt"); // opens the file
if( !outdata ) { // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
for (int i=0; i<4; i++) {
outdata <<setw(21)<<left<< users[i] << votes[i] << endl;
}
outdata<<left<<"-----------------------"<<endl;
outdata<<setw(21)<<left<<"Total Votes: "<<totalVotes<<endl;
outdata.close();
getch();
return 0;
}
How can i optimize this program? i know there is a way to do that (pointers etc.) , but i don't know how) , Can somebody tell me what must i do? Thanks in advance.