I am writing one of my first programs which reads from a file and allows you to play a game, I have been told the exit function is not a good idea.
I am trying to call back to main in order to close the program correctly but I get the following error:
C3861 'main': identifier not found.
any ideas where I went wrong or how I can properly call the main function?
Code Below:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void extra() {
int lives = 3;
int UI, intAnswer;
int opt = 0;
string IN, NoQ, q, c1, c2, c3, Answer;
fstream quiz;
cout << "Welcome to the guessing game!" << endl;
quiz.open("QuizQuestions.txt");
getline(quiz, IN);
cout << "There are " << IN << " Questions" << endl;
while (quiz.good() && opt !=2) {
getline(quiz, q);
cout << "Question " << q << endl;
getline(quiz, c1);
cout << c1 << endl;
getline(quiz, c2);
cout << c2 << endl;
getline(quiz, c3);
cout << c3 << endl;
getline(quiz, Answer);
intAnswer = stoi(Answer);
cout << "What answer do you think it is? ";
cin >> UI;
if (UI == intAnswer) {
lives++;
cout << "You got it right! You now have " << lives << " lives left " << endl << endl;
//i = 0;
}
else {
cout << "You got the answer wrong sorry, the correct answer is " << Answer << endl;
lives--;
cout << "You now have " << lives << " lives" << endl;
//i = 0;
if (lives < 1) {
cout << "You lose, would you like to play again? 1 for yes, 2 for no? ";
cin >> opt;
if (opt = 1) {
cout << endl;
extra();
}
else if (opt = 2) {
quiz.close();
return;
}
}
}
}
quiz.close();
}
int main() {
int UI;
cout << "Would you like to do the quiz? 1 - yes other - no ";
cin >> UI;
if (UI = 1) {
extra();
}
return 0;
}
You can't call main yourself.
When you call a function and it gets to the end, the function pointer/flow will return to the calling code.
Let's consider the general structure of your code:
void extra() {
for (int i = 0; i = 1; i++) {
//^---I suspect you don't mean this, maybe i<1, or 3, or...
// recall == and -= are different
//snipped some details
if (UI == intAnswer) {
lives++;
cout << "You got it right! You now have " << lives << " lives left " << endl << endl;
i = 0;
}
else {
cout << "You got the answer wrong sorry, the correct answer is " << Answer << endl;
lives--;
cout << "You now have " << lives << " lives" << endl;
i = 0;
if (lives < 1) {
cout << "You lose, would you like to play again? 1 for yes, 2 for no? ";
cin >> UI;
if (UI = 1) {
cout << endl;
extra();
//^--- I suspect you don't need this recursive call
}
else {
quiz.close();
return;
// ^---- return back to where we started
}
}
}
}
}
quiz.close();
system("pause");
}
int main() {
int UI;
cout << "Would you like to do the quiz? 1 - yes other - no ";
cin >> UI;
if (UI = 1) {
extra();//we come back here after the function stops
}
return 0;
}
Note I have simply put return where you want to end the function/program.
Instead of calling main, you can simply return from the extra function. The program then continues execution from where you called extra.
Just return to main.
else {
quiz.close();
𝙧𝙚𝙩𝙪𝙧𝙣;
}
Related
#pragma once
#ifndef SDDS_GIFT_H
#define SDDS_GIFT_H
#include <iostream>
namespace sdds
{
const int MAX_DESC = 15;
const double MAX_PRICE = 999.999;
const int MAX_WRAP = 20;
struct Gift
{
char m_description[MAX_DESC];
double m_price;
int m_units;
int m_wrapLayers;
struct Wrapping* m_wrap;
};
struct Wrapping
{
char* m_pattern;
};
void gifting(char*);
void gifting(double&);
void gifting(int&);
bool wrap(Gift& theGift);
bool unwrap(Gift& theGift);
void gifting(Gift& theGift);
void display(const Gift& theGift);
}
#endif
<pre><code>
#include <iostream>
#include "Gift.h"
using namespace std;
namespace sdds
{
void gifting(char* m_description) // sending info
{
cout << "Enter gift description: ";
cin.width(MAX_DESC + 1);
cin >> m_description;
}
void gifting(double& m_price)
{
cout << "Enter gift price: ";
cin >> m_price;
while (m_price > MAX_PRICE || m_price < 0)
{
cout << "Gift price must be between 0 and " << MAX_PRICE << std::endl;
cout << "Enter gift price: ";
cin >> m_price;
}
}
void gifting(int& m_units)// gifting function
{
cout << "Enter gift units: ";
cin >> m_units;
while (m_units < 1)
{
cout << "Gift units must be at least 1" << std::endl;
cout << "Enter gift units: ";
cin >> m_units;
};
}
bool wrap(Gift& m_wrap) {
if (m_wrap.m_wrapLayers > 0) {
cout << "Gift is already wrapped!" << endl;
return false;
}
else {
cout << "Wrapping gifts..." << endl;
cout << "Enter the number of wrapping layers for the Gift: ";
cin >> m_wrap.m_wrapLayers;
while (m_wrap.m_wrapLayers < 1) {
cout << "Layers at minimum must be 1, try again." << endl;
cout << "Enter the number of wrapping layers for the Gift: ";
cin >> m_wrap.m_wrapLayers;
}
int i = 0;
m_wrap.m_wrap = new Wrapping[MAX_WRAP + 1];
for (i = 0; i < m_wrap.m_wrapLayers; i++) {
m_wrap.m_wrap->m_pattern = new char[MAX_WRAP + 1];
cout << "Enter wrapping pattern #" << i + 1 << ": ";
cin >> m_wrap.m_wrap->m_pattern;
} // I put struct in a structure
return true;
}
delete[]m_wrap.m_wrap;
m_wrap.m_wrap = nullptr;
}
bool unwrap(Gift& g_unwrap) // unwrap function
{
if (g_unwrap.m_wrapLayers > 0) {
cout << "Gift being unwrapped." << endl;
g_unwrap.m_wrapLayers = 0;
g_unwrap.m_wrap->m_pattern = nullptr;
return true;
}
else
{
cout << "Gift isn't wrapped! Can't unwrap." << endl;
return false;
}
}
void display(const Gift& theGift)
{
cout << "Gift Details:" << endl;
cout << " Description: " << theGift.m_description << endl;
cout << " Price: " << theGift.m_price << endl;
cout << " Units: " << theGift.m_units << endl;
if (theGift.m_wrap == nullptr) // this part seems like a problem
{
cout << "Unwrapped" << endl;
}
else
{
int i = 0;
cout << "Wrap Layers: " << theGift.m_wrapLayers << endl;
for (i = 0; i < theGift.m_wrapLayers; i++) {
cout << "Wrap #" << i + 1 << ": " << theGift.m_wrap[i].m_pattern << endl;
}
}
}
void gifting(Gift& gift) //last function
{
cout << "Preparing a gift..." << endl;
gifting(gift.m_description);
gifting(gift.m_price);
gifting(gift.m_units);
wrap(gift);
}
}
</code></pre>
/***********************************************************************
// Workshop 2: Dynamic Memory & Function Overloading
// Version 2.0
// Date 2020/05/05
// Author Michael Huang
// Description
// Tests Gift module and provides a set of TODOs to complete
// which the main focuses are dynamic memory allocation
//
/////////////////////////////////////////////////////////////////
***********************************************************************/
#include <iostream>
#include "Gift.h"
#include "Gift.h" // intentional
using namespace std;
using namespace sdds;
void printHeader(const char* title)
{
char oldFill = cout.fill('-');
cout.width(40);
cout << "" << endl;
cout << "|> " << title << endl;
cout.fill('-');
cout.width(40);
cout << "" << endl;
cout.fill(oldFill);
}
<pre><code>
int main() {
Gift g1; // Unwrapped Gift
{
printHeader("T1: Checking Constants");
cout << "MAX_DESC: " << sdds::MAX_DESC << endl;
cout << "MAX_PRICE: " << sdds::MAX_PRICE << endl;
cout << "MAX_WRAP: " << sdds::MAX_WRAP << endl;
cout << endl;
}
{
printHeader("T2: Display Wrapped Gift");
gifting(g1.m_description);
gifting(g1.m_price);
gifting(g1.m_units);
cout << endl;
g1.m_wrap = nullptr;
g1.m_wrapLayers = 0;
display(g1);
cout << endl;
}
{
printHeader("T3: Wrap a gift");
if (wrap(g1))
cout << "Test succeeded!";
else
cout << "Test failed: wrapping didn't happen!" << endl;
cout << endl << endl;
}
{
printHeader("T4: Re-wrap a gift");
cout << "Attempting to rewrap the previous Gift: "
<< g1.m_description << endl;
if (wrap(g1) == false)
cout << "Test succeeded!";
else
cout << "Test failed: gift it's already wrapped, cannot wrap again!";
cout << endl << endl;
}
{
printHeader("T5: Unwrap a gift");
cout << "Attempting to unwrap the previous gift: "
<< g1.m_description << endl;
if (unwrap(g1))
cout << "Test succeeded!";
else
cout << "Test failed: you should be able to unwrap!";
cout << endl << endl;
}
{
printHeader("T6: Unwrap again");
cout << "Attempting to un-unwrap the previous gift: "
<< g1.m_description << endl;
if (!unwrap(g1))
cout << "Test succeeded!";
else
cout << "Test failed: you should not be able to unwrap again!";
cout << endl << endl;
}
Gift g2; // Unwrapped Gift
{
printHeader("T7: Prepare another gift");
g2.m_wrap = nullptr;
g2.m_wrapLayers = 0;
gifting(g2);
cout << endl;
display(g2);
cout << endl;
}
{
printHeader("T8: Unwrap the second gift");
unwrap(g2);
}
return 0;
}
Output matches perfectly but I don't know why memory leaks.. please help me. I am doubting my wrap part but I think there must be something else since deallocation seems fine.
I tried my best but I still cannot see which part is wrong.
I cannot see why my deallocation does not work I tried changing it so many times but nothing works.
On this line:
m_wrap.m_wrap->m_pattern = new char[MAX_WRAP + 1];
You allocate memory, but later you only:
delete[]m_wrap.m_wrap;
Also in your for loop you allocate memory, then get some input and store that inside the pointer, as a memory address. Should you ever dereference that, you will invoke undefined behavior, in practice that may likely will a segfault. You should consider rewriting at least that part from scratch.
Program should begin with asking , whether to restock or continue with the current stock. The case 1 ( restock ) works perfectly , however the second case , to continue with the previous stock , returns zeros always if any of the products is zeroed.
In the textfile I have:
Milk: 10
Eggs: 2
Water: 7
Burrito: 10
Bread: 12
exit
How can i fix that ?
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
string productName[5] = { "Milk", "Eggs", "Water", "Burrito", "Bread" };
//int productAmount[5] = { 5,12,10,4,7};
int productAmount[5];
int productPick;
int defaultPick;
int productBuy;
fstream productFile; //we create file
void loadFromFile()
{
productFile.open("productsfile.txt", ios::in);
if (productFile.good() == false)
{
cout << "Unable to load the file. Try again later." << endl;
productFile.close();
exit(0);
}
else
{
ifstream productFile("productsfile.txt");
if (productFile.is_open())
{
cout << "How may I help you?" << endl;
string line;
while (getline(productFile, line))
{
// using printf() in all tests for consistency
cout << line.c_str() << endl;
}
productFile.close();
}
}
}
void saveToFile() //this function saves in the text file the data we've globally declared. It is used only if you want to declare new variables.
{
productFile.open("productsfile.txt", ios::out);
for (int i = 0; i < 5; i++)
{
productFile << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
productFile << "6. Exit" << endl;
productFile.close();
}
void askIfDefault()
{
cout << "Do you want to come back to default stock?" << endl;
cout << "1. Yes " << "2. No " << endl;
cin >> defaultPick;
switch (defaultPick)
{
case 1:
for (int i = 0;i < 5;i++)
{
productAmount[i] = 10;
}
saveToFile();
loadFromFile();
break;
case 2:
loadFromFile();
break;
default:
cout << "I don't understand." << endl;
exit(0);
break;
}
}
void productCheck()
{
if (productAmount[productPick - 1] <= 0 || productAmount[productPick - 1] < productBuy)
{
cout << "Unfortunately we have no more " << productName[productPick - 1] << " in stock. Please choose other product from the list below: " << endl;
productAmount[productPick - 1] = 0;
}
else
{
productAmount[productPick - 1] -= productBuy;
}
}
void listOfProducts()
{
cout << "How may I help you?" << endl;
for (int i = 0; i < 5; i++)
{
cout << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
cout << "6. Exit" << endl;
}
void order()
{
cin >> productPick;
switch (productPick)
{
case 1:
cout << "How many bottles?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 2:
cout << "How many cartons?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 3:
cout << "How many multi-packs?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 4:
cout << "How many portions?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 5:
cout << "How many batches?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 6:
cout << "See you soon!" << endl;
saveToFile();
system("pause");
break;
case 666:
cout << "You cannot use the secret magic spells here." << endl;
saveToFile();
exit(0);
break;
default:
cout << "Please pick the existing product: " << endl;
saveToFile();
order();
break;
}
}
int main()
{
askIfDefault();
order();
cout << endl;
while (true && productPick != 6)
{
listOfProducts();
order();
saveToFile();
cout << endl;
}
return 0;
}
Maybe unless declaring one global fsteam productFile, try to declare the it inside each of both functions that are using it: 'loadFromFile()' and 'saveToFile()' respectively. At the beginning of them. It should be fine then.
Let me make a few additional suggestions about your code - because it's a bit difficult to follow:
Choose function names which reflect what the function does - and don't do anything in a function which exceeds what its name indicates. For example, if you wrote a function called ask_whether_to_restock() - that function should ask the question, and perhaps even get the answer , but not actually restock even if the answer was "yes" - nor write anything to files. Even reading information from a file is a bit excessive.
If you need to do more in a function than its name suggests - write another function for the extra work, and yet another function which calls each of the first two and combines what they do. For example, determine_whether_to_restock() could call read_current_stock_state() which reads from a file, and also print_stock_state() and, say, get_user_restocking_choice().
Try to avoid global variables. Prefer passing each function those variables which it needs to use (or references/pointers to them if necessary).
Don't Repeat Yourself (DRI): Instead of your repetitive switch(produtPick) statement - try writing something using the following:
cout << "How many " << unit_name_plural[productPick] << "?" << endl;
with an additional array of strings with "bottles", "cans", "portions" etc.
Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.
I am trying to add a countdown timer to this program. I would like the timer to start when the first math fact question is asked and upon expiration i want the program to give the grade. What's the code to do this in c++ if possible?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
int main(int args, char* argv[])
{
int i;
int result;
int solution;
char fact;
bool done = false;
int correct = 0;
int count = 0;
do {
try {
cout << "Enter (m)ultiplication or "
<< "(a)ddition." << endl; /*or (s)ubstraction. */
cin >> fact;
while (!cin)
throw fact;
if (fact != 'A')
if (fact != 'a')
if (fact != 'M')
if (fact != 'm')
while (!cin)
throw fact;
cout << "Now, enter the number of the fact that
you would like to do." << endl;
cin >> i;
int wrong = 0;
int score = 0;
int j = 0;
while (!cin)
throw i;
switch (fact) {
case 'm':
case 'M':
while (j < 13) {
cout << "What's " << i << " x " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i * j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " x " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " x " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i * j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
case 'a':
case 'A':
while (j < 13) {
cout << "What's " << i << " + " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i + j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " + " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " + " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i + j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
if (j == 13) {
system("pause");
correct = score - wrong;
score = (correct * 100) / 13;
}
if (score >= 80) {
cout << "Excellent!!!!!" << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Keep up the good work." << endl;
} else if (score >= 70) {
cout << "Congratulations!!!!!" << endl
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Let's see if we can score even higher next time." << endl;
} else {
cout << "You scored below 70 which means that you may need some"
<< " more practice." << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "You might want to try the " << i << " facts again."
<< " Goodluck!!!!!" << endl;
}
}
} catch (char fact) {
cout << "Invalid input. You can only enter (m)ultiplication or"
<< " (a)ddition. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (int i) {
cout << "Invalid input0. You can only enter a
number here. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (...) {
cout << "Invalid input2. You can only enter a number here.
Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
}
} while (!done);
return 0;
}
The task is quite hard, but if you dare trying, I suggest doing it in two steps:
Implement inaccurate solution: timer expiration is checked between queries to user.
If there is some time left, next question is asked, otherwise statistics is shown. So program always waits for user input on the last question despite timer has run out. Not what exactly quizzes look like, but good move to start with.
Method: before starting quiz save current time, before each question take delta between saved time and current one and compare with time limit. Example with chrono (starting from C++11), example with oldschool clock
Add middle-question interruption
This part requires function, which will wait for user input not longer, than specified amount of time. So instead of using std::cin() you'll need to calculate amount of time left (time limit minus delta between cur time and start time) and call some sort of cin_with_timeout(time_left).
The hardest thing is implementing cin_with_timeout(), which requires solid knowledge of multithreading and thread synchronization. Great inspiration can be found here, but it is direction to start thinking rather than complete solution.
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;
}
}