debug error heap corruption c++ pointers - c++

so i have this assignment that tells the user to input two numbers and lets him choose some basic operations(like a calculator) from a menu.
The goal of this exercise is to help us get more familiar with pointers/pointers to functions/dynamic allocation...The professor prefers that we use the "malloc" and "calloc" commands.
There is a part I'm stuck on, the part of displaying the history. It works for the first execution, but gives a debugging error as the code proceeds. Is there anyone who can help me solve the issue?
c++ code:
#include <iostream>
using namespace std;
//structure for the history array
struct Operation{
float result;
int choice;
};
float add(float, float);
float sub(float, float);
float mult(float, float);
float divi(float, float);
int main(){
//size1=for 1st history array, size2=for 2nd history array, t=to check if an operation was done at least once
int choice,size1=0,t=0,i,size2=0;
//pointer to func
int(*operation)(int, int);
float a, b,result;
//pointers set to NULL
Operation *history1 = NULL, *history1i = NULL, *history2 = NULL, *history2i = NULL;
cout << "Enter 2 numbers a & b: ";
cin >> a >> b;
cout << "What would you like to do?" << endl << "1=Addition" << endl << "2=Subtraction" << endl << "3=Division" << endl;
cout << "4=Multiplication" << endl << "5=Display History" << endl << "6=Exit" << endl;
do{
cin >> choice;
//initialize the size of 1st array if a choice is valid
if (choice < 5 && choice >0)
size1++;
//initialize 1st array
history1 = (Operation*)calloc(size1, sizeof(Operation));
if (history1 == NULL){
cout << "History allocation failed."<<endl;
exit(0);
}
//menu
switch (choice){
case 1: result = (add)(a, b);
cout << endl << "The addition of " << a << " & " << b << " gives: " << result << endl;
break;
case 2:result = (sub)(a, b);
cout << endl << "The subtraction of " << a << " & " << b << " gives: " << result << endl;
break;
case 3:if (b != 0){
result = (divi)(a, b);
cout << endl << "The division of " << a << " & " << b << " gives: " << result << endl;
}
else
cout << "Can't perform the divison.";
break;
case 4:result = (mult)(a, b);
cout << endl << "The multiplication of " << a << " & " << b << " gives: " << result << endl;
break;
//display history
case 5:if (t == 1){
cout << endl << "Your history is: " << endl;
for (history2i = history2,i=1; (history2i - history2) < size2; history2i++,i++){
cout << "\t"<<i<<"- " << a;
if (history2i->choice == 1)
cout << " + ";
else if (history2i->choice == 2)
cout << " - ";
else if (history2i->choice == 3)
cout << " / ";
else
cout << " * ";
cout << b << " = " << history2i->result<<endl;
}
}
else
cout <<endl<< "You haven't done any calcualtions yet."<<endl;
break;
case 6:break;
default:cout << endl << "The option you entered is not valid." << endl;
break;
}
//if choice is valid
if (choice < 5 && choice >0){
//if at least one opertion executed copy the elements of history2 in history1
if (t == 1){
for (history1i = history1, history2i = history2; (history1i - history1) < size2; history1i++, history2i++){
history1i->result = history2i->result;
history1i->choice = history2i->choice;
}
history1i++;//in order to enter the new operation
}
//if no operation done
else{
history1i = history1;
}
history1i->result = result;
history1i->choice = choice;
}
//if at least one operation done=>history exists and not NULL
if (t == 1){
free(history2);//in order to create a new array with the new elements
history2 = NULL;
}
//if not operations done before increment t
if (choice < 5 && choice >0 && t == 0){
t++;
}
//if valid choice create history 2
if (choice < 5 && choice >0){
size2 = size1;
history2 = (Operation*)calloc(size2, sizeof(Operation));
if (history2 == NULL){
cout << "History allocation failed." << endl;
exit(0);
}
//store all the previous history including the new one
for (history2i = history2, history1i = history1; (history2i - history2) < size2; history2i++, history1i++){
history2i->result = history1i->result;
history2i->choice = history1i->choice;
}
}
free(history1);
history1 = NULL;
if (choice != 6)
cout << endl << "Choose another option: ";
} while (choice != 6);
return 0;
}
float add(float a, float b){
return a + b;
}
float sub(float a, float b){
return a - b;
}
float mult(float a, float b){
return a*b;
}
float divi(float a, float b){
return a / b;
}

Related

I am here to ask on how can I store the calculation history of my calculator in c++

I am new to the coding community and I am here to ask on how can I store the calculations that have been done in my calculator. I am currently new in this space and I am currently looking for answers T-T.
my code goes like this thank you everyone! T-T pls be gentle on me.
#include<iostream>
#include<stdlib.h>
using namespace std;
int calculator();
void history();
void choice();
int main()
{
int x;
cout << "\t\t\t\tWhat do you want to do?\n\n";
cout << "\t\t\t\t[1] Standard calculator\n";
cout << "\t\t\t\t[2] History\n";
cout << "\t\t\t\t[3] Exit\n\n\n\n";
cout << "\t\t\t\tChoice: ";
cin >> x;
switch (x)
{
case 1:
calculator();
break;
case 2:
history();
break;
case 3:
cout << "\n\n\nThank you for using my calculator!";
exit(4);
break;
default:
cout << "Enter a correct choice";
main();
}
}
int calculator()
{
double x, y;
float sum = 0.0, dif = 0.0, prod = 1.0, quo = 1.0;
int i;
char op, back;
do {
system("CLS");
cout << "\t\t#CALCULATOR#" << endl;
cout << endl << endl;
cout << "Calculate 2 numbers: (example 1 + 1 or 2 * 2)\n";
cin >> x >> op >> y;
switch (op) {
case '+':
sum = x + y;
cout << "The sum of " << x << " and " << y << " is " << sum;
break;
case '-':
dif = x - y;
cout << "The difference of " << x << " and " << y << " is " << dif;
break;
case '*':
prod = x * y;
cout << "The product of " << x << " and " << y << " is " << prod;
break;
case '/':
if (y == 0)
cout << "Undefined";
else
quo = x / y;
cout << "The quotient of " << x << " and " << y << " is " << quo;
break;
default:
cout << "Invalid operator";
break;
}
cout << "\nContinue[Y/N]: ";
cin >> back;
cout << endl << endl;
if (back != 'Y' && back != 'y' && back != 'N' && back != 'n')
{
cout << "Please enter a correct choice" << endl;
choice();
}
else if (back == 'N' || back == 'n')
{
system("pause");
system("CLS");
main();
}
} while (back == 'y' || back == 'Y');
cout << "Thank you";
system("pause");
system("CLS");
}
void choice()
{
char c;
do
{
cout << "Do you want to continue? [Y/y or N/n]" << endl;
cin >> c;
if (c == 'Y' || c == 'y')
calculator();
else if (c == 'N' || c == 'n')
{
system("pause");
system("cls");
main();
}
else
cout << "Please enter a correct choice\n";
choice();
} while (c != 'y' || c != 'Y' || c != 'N' || c != 'n');
cout << "Enter a correct choice";
}
void history()
{
cout << "I still dont know how T - T";
}
I wanted to store the past calculations using arrays but i dont know how to actually put it in my code T-T pls help
You want to #include <vector> and make a history std::vector, that holds strings:
std::vector<std::string> history;
When you do the calculcation, don't output to cout, but to a std::ostringstream first (located in <sstream>):
std::ostringstream caclulation_stream;
switch (op) {
case '+':
sum = x + y;
caclulation_stream << "The sum of " << x << " and " << y << " is " << sum;
break;
case '-':
dif = x - y;
caclulation_stream << "The difference of " << x << " and " << y << " is " << dif;
break;
case '*':
prod = x * y;
caclulation_stream << "The product of " << x << " and " << y << " is " << prod;
break;
case '/':
if (y == 0)
caclulation_stream << "Undefined";
else
quo = x / y;
caclulation_stream << "The quotient of " << x << " and " << y << " is " << quo;
break;
default:
caclulation_stream << "Invalid operator";
break;
}
this way, you can save the string to history. push_back() adds the string to the vector. Don't forget to also print out the string, so it's still displayed in the console.
auto calculation_string = caclulation_stream.str();
history.push_back(calculation_string);
std::cout << calculation_string;
to display the history, you can loop over the vector and print out the elements:
void show_history()
{
for (const auto& entry : history) {
std::cout << entry << '\n';
}
}
this should give you the basic ideas on how to implement this.
Read here why you shouldn't be using namespace std;.

C++ Left Center Right Dice Game (Game Loop and connecting vectors/arrays to classes/header files)

So i have to code the dice game LCR for a final prject but am having some trouble. First off, I know the code is sloppy and really redundant, that's why im looking for help. I couldn't figure out how to connect the 'chips' int vector and 'name' array into the player.h file. I basically need help writing methods for the chip passing to make the code less redundant. But another problem of mine is having the game loop until just one person has chips. Thanks for any help or advice.
LeftCenterRight.cpp
#include <iostream>
#include <string>
#include <time.h>
#include "Dice.h"
#include "Player.h"
#include <vector>
#include <algorithm>
using namespace std;
void Player::gameRules()
{
cout << ("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n");
cout << ("Left Center Right is a multiplayer dice game");
cout << ("With a minimum of three players.");
cout << ("Dice containing letters L, C, R along\n"
"with dots on the remaining side are rolled each turn");
cout << ("\n-----Each Player starts with three chips-----\n");
cout << (">> For each L rolled, the player must pass one chip to the player to their left\n"
">> For each R rolled, the player must pass one chip to the player to their right\n"
">> For each C rolled, the player must pass a chip into the center pot (out of play)\n"
">> Dots are neutral and require no action");
cout << ("If a player has three or more chips, he/she rolls all three dice\n"
"If a player only has two chips, he/she rolles onlt two dice\n"
"If a player only has one chip, he/she rolls only one die\n"
"If a player is out of chips, he/she is still in the game,\n"
"\tbut does not roll any dice and passes their turn"
"\n\n >>> The last player with chips is the winner <<<");
cout << ("\n\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
};
int main()
{
int result = 0;
int currPlayer = 1;
srand((unsigned)time(NULL));
int numPlayers;
cout << "How many players are playing? (Please enter 3 or more): " << endl;
cin >> numPlayers;
if (numPlayers <= 2)
{
while (numPlayers <= 2)
{
cout << "More players needed.";
cout << "How many players are player?: ";
cin >> numPlayers;
}
}
std::string* names = new string[numPlayers]; // getting names and index is seat number
for (int i = 0; i < numPlayers; i++)
{
cout << "Please enter your name player " << i+1 << endl;
cin >> names[i];
std::string playerName = names[i];
}
vector<int>chips[1]; // intial 3 chips
for (int i = 0; i < numPlayers; i++)
{
int InitialChips = 3;
chips->push_back(InitialChips);
}
Player::gameRules();
int sum = 0;
for (int i = 0; i < chips->size(); i++)
{
int num = chips->at(i);
sum+=num;
}
int thePot = 0;
int i = 0;
while (sum > 0)
{
if ( i >=4 )
{
i = 0;
}
string currPlayer = names[i];
int currSeat = i;
cout << "It's " << currPlayer << "'s Turn!" << endl;
cout << "[1] Roll Dice [2] Quit :";
int choice;
cin >> choice;
if (choice == 1)
{
if (chips->at(currSeat) == 0)
{
break;
}
if (chips->at(currSeat) >= 3)
{
for (int k = 0; k <= 3; k++)
{
int outcome = Dice::rollDice();
if (outcome == 1)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == 0)
{
int j = (numPlayers - 1);
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i - 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 2)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == chips->size())
{
int j = chips->at(0);
int currChips2 = chips->at(0);
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i + 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 3)
{
thePot++;
cout << ">> +1 chip to the Center Pot" << endl;
cout << "There are now " << thePot << " chip(s) in the Center Pot " << endl;
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
break;
}
else if ((outcome == 4) || (outcome == 5) || (outcome == 6))
{
break;
}
}
}
// ^^basically copied and pasted most of the while loop for the other two numbers of dice to roll^^
// had redundant code for if the player had 2 chips, to roll two dice only ^^
// also redundant code for only one chip, to roll one die. ^^
}
}
else if (choice == 2)
{
break;
}
else
{
cout << ">> Input Error";
cout << "[1] Roll Dice [2] Quit";
cin >> choice;
}
i++;
}
return 0;
}
Dice.h
#pragma once
using namespace std;
class Dice
{
public:
static int rollDice();
static int diceOutcome;
};
int Dice::rollDice()
{
int diceOutcome;
diceOutcome = (rand() % 6) + 1;
switch (diceOutcome)
{
default:
cout << "Error, retry";
case 1:
if (diceOutcome == 1)
{
cout << " --- " << endl;
cout << "You rolled a | L | Move 1 chip left." << endl;
cout << " --- " << endl;
return 1;
}
break;
case 2:
if (diceOutcome == 2)
{
cout << " --- " << endl;
cout << "You rolled a | R | Move 1 chip right." << endl;
cout << " --- " << endl;
return 2;
}
break;
case 3:
if (diceOutcome == 3)
{
cout << " --- " << endl;
cout << "You rolled a | C | Move 1 chip to the center." << endl;
cout << " --- " << endl;
return 3;
}
break;
case 4:
if (diceOutcome == 4)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 5:
if (diceOutcome == 5)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 6:
if (diceOutcome == 6)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
}
}
To be fair, I'm quite new to programming, but I have been working on this project for days and kept running into conatiner problems and storing the name and chip values independently. So i've tried a lot of different things, probably not correctly though so I'm open to anything.

I am getting errors in my C++ program

I am current creating a weather application that is giving me an error. It said there is something wrong with != but I am not sure what is wrong so can anyone help. It is giving me the error operand types are incompatible ("std::string *" and "const char *")(there is 4) and '!=': no conversion from 'const char *' to 'std::string *'
Thank you
C++ code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void moveTemperaturesToRight(double temperatures[], double windSpeed[], string windDirection[])
{
for (int i = 3; i > 0; i--)
{
temperatures[i] = temperatures[i - 1];
windSpeed[i] = windSpeed[i - 1];
windDirection[i] = windDirection[i - 1];
}
}
int main()
{
string name;
int choice;
int numOfReadings = 0;
double temperatures[4], windSpeeds[4];
string windDirections[4];
bool initialized = false;
string str;
//Have the user provide a name for the weather station upon entry.
cout << "Enter the name of weather station: ";
getline(cin, name);
//Control loop to perform various actions.
while (true)
{
cout << "1. Input a complete weather reading." << endl;
cout << "2. Print the current weather." << endl;
cout << "3. Print the weather history (from most recent to oldest)." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter your choice: ";
cin >> str;
if (str.length() != 1 || str < "1" || str > "4")
choice = 0;
else
choice = atoi(str.c_str());
//Switch based on choice.
switch (choice)
{
case 1: moveTemperaturesToRight(temperatures, windSpeeds, windDirections);
do {
cout << "Enter the temperature (a value >=0):";
cin >> temperatures[0];
} while (temperatures < 0);
//get correct wind speed
do
{
cout << "Enter the wind speed (a value >=0):";
cin >> windSpeeds[0];
} while (windSpeeds < 0);
//get correct wind direction
do
{
cout << "Enter the wind direction (North,South,East or West):";
cin >> windDirections[0];
} while (windDirections != "North" && windDirections != "South" && windDirections != "East" && windDirections != "West");
initialized = true;
if(initialized)
numOfReadings++;
if (numOfReadings > 4)
numOfReadings = 4;
break;
case 3: //Print the current weather, if valid weather is entered.
for (int i = 0; i < numOfReadings; i++)
{
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[i] << endl;
cout << "Wind speed: " << windSpeeds[i] << endl;
cout << "Wind direction: " << windDirections[i] << endl << endl;
}
if (numOfReadings == 0)
cout << "Please enter the details before asking to print." << endl;
break;
case 2: if (numOfReadings == 0)
{
cout << "Please enter the details before asking to print." << endl;
break;
}
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[0] << endl;
cout << "Wind speed: " << windSpeeds[0] << endl;
cout << "Wind direction: " << windDirections[0] << endl << endl;
break;
case 4: return 0; //Stops execution.
default: cout << "Invalid choice. Please follow the menu." << endl;
}
}
}
You need to compare an element of windDirections with the literal.
Did you mean windDirections[0] != "North" &c.?
Currently you're attempting to compare an array of std::strings, and so the compiler issues a diagnostic. It does its best in decaying the array to a pointer to std::string (hence the specific error), but then gives up.

How is this specific vector working?

Hello i got this code which is working fine but i fail to understand some parts of it and i could really use some help if anyone has some time to spare. I dont understand why is there a pointer *hightway on vector and why is there a star in vector? None of the vectors i found use stars. Even the slightest of help is welcome, thanks in advance.
int main() {
int menuSelection,entryPoint,exitPoint,vehicleType;
string plate,entryTime,exitTime;
Vehicle * v = NULL;
vector<Vehicle *> * highway;
highway = new vector<Vehicle*>;
do {
mainMenu:
cout << "\n\n\tKENTPIKO MENOY\n";
cout << "\t[1] Eisodos oximatos\n";
cout << "\t[2] Eksodos oximatos\n";
cout << "\t[0] Eksodos apo to programma\n\n";
cout << "\tEpilogi: ";
cin >> menuSelection;
switch(menuSelection) {
case 0:
cout << "\n\nEuxaristoume pou xrisimopoihsate to programma mas!";
return 0;
case 1:
cout << "\n\n\tEISODOS OXIMATOS";
do {
cout << "\n\tSe poio simeio briskeste ; (1 ews 3) \t";
cin >> entryPoint;
} while(entryPoint > 3 || entryPoint == 0);
cout << "\n\tArithmos kukloforias: ";
cin >> plate;
cout << "\n\tTupos oximatos\t";
cout << "\n\t1: Dikikla\t2:Autokinita\t3:Fortiga\n";
do {
cout << "\tEpilogi: ";
cin >> vehicleType;
}while (vehicleType > 3 || vehicleType == 0);
cout << endl;
if (vehicleType==1){
v = new Motorcycle();
}
else if (vehicleType==2){
v = new Car();
}
else if (vehicleType==3){
v = new Truck();
}
v->setPlate(plate);
v->setEntryPoint(entryPoint);
v->setEntryTime(getTime());
highway->push_back(v);
cout << "\n\n\tTo autokinito mpike stis " << v->getEntryTime() << " apo to simeio " << v->getEntryPoint();
cout << "\n\n\tParakalo paralabate to eisitirio";
v = 0;
goto mainMenu;
case 2:
cout << "\n\n\tEKSODOS OXIMATOS";
cout << "\n\tArithmos kukloforias: ";
cin >> plate;
for(vector<Vehicle*>::iterator it = highway->begin(); it != highway->end(); it++){
if (plate.compare((*it)->getPlate()) == 0){
do {
cout << "\n\tSe poio shmeio briskeste; (" << (*it)->getEntryPoint()+1 <<" ews 4) \t";
cin >> exitPoint;
}while(exitPoint > 4 || exitPoint <= (*it)->getEntryPoint());
(*it)->setExitPoint(exitPoint);
(*it)->setExitTime(getTime());
cout << "\tArithmos kukloforias: " << (*it)->getPlate() << endl << endl;
cout << "\tSimeio eisodou: " << (*it)->getEntryPoint() << endl;
cout << "\tOra eisodou : " << (*it)->getEntryTime() << endl;
cout << "\tSimeio eksodou : " << (*it)->getExitPoint() << endl;
cout << "\tOra eksodou : " << (*it)->getExitTime() << endl << endl;
cout << "\tSinoliki apostasi: " << (*it)->totalDistance() << "km"<< endl;
double km;
km=(*it)->totalFee()/(*it)->totalDistance();
cout << "\n\tkostos ana klm: " << km;
cout << "\n\n\tSINOLIKO POSO: " << (*it)->totalFee();
cout << "\n\n\tH apodeiksi einai ston ektupoti";
}
else {
cout << "\n\nTO OXIMA DEN YPARXEI!" << endl;
break;
}
}
goto mainMenu;
default:
cout << "\n\n\tLATHOS EPILOGI! Dokimaste ksana.\n\n";
goto mainMenu;
}
} while (menuSelection != 0);
return 0;
}
I dont understand why is there a pointer *hightway on vector
because its a pointer to vector<Vehicle *>, in line highway = new vector<Vehicle*>; you see that it is initialized with pointer to memory allocated with new.
and why is there a star in vector?
you mean in Vehicle* ? it because this vector contains pointers to Vehicle objects. Each element is a pointer to some dynamically allocated Vehicle object.
You dont really need highway to be a pointer, you may use:
vector<Vehicle *> highway;
and later on use highway.push_back instead of highway->push_back.

C++ program to display votes in percentage not showing correct result

I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}