This program I came across on another forum is a voting program, someone was having issues with compiling. Any answer that was given didn't really match up with what the programmer wanted. So I am here to get some effective answers after attempting to edit the code myself.
The current issue I am having is when I input the variable, it still runs an infinite loop. What am I not doing properly for the design to perform, until I input 5 votes?
#include <iostream>
using namespace std;
const int ev = 5; //max. # of votes
int votesA = 0, votesB = 0, votesC = 0, spoiltvotes = 0; //total votes already initialized globally
int vote; //input variable
int main()
{
//loop over the voting stations
int i;
for(i = 0; i <= ev; i++)
{
//loop over the votes
cout << "Enter your vote: \t";
cin >> vote;
while(vote <= 5)
{
switch(vote)
{
case 1: votesA++;
break;
case 2: votesB++;
break;
case 3: votesC++;
break;
default: spoiltvotes++;
}
}
}
//display results neatly
cout << "# of votes for candidate A: \t" << votesA;
cout << "\n # of votes for candidate B: \t" << votesB;
cout << "\n # of votes for candidate C: \t" << votesC;
cout << "\n # of spoilt votes: \t" << spoiltvotes;
return 0;
}
Updated Result: I have fixed the infinite loop but for some reason the loop is still iterating 6 times instead of 5, giving me large tallies of numbers instead of single-digits.
#include <iostream>
using namespace std;
int main()
{
const int ENDvote = 5; //max. # of votes
//loop over the voting stations
int vote;
int spoiltvotes;
for(vote = 0; vote >= ENDvote; vote++)
cout << "1. Candidate A\t 2. Candidate B\t 3. Candidate C" << endl;
{
//loop over the votes
cout << "Enter your vote: \t";
cin >> vote;
switch(vote)
{
case 1:
cout << "# of votes for candidate A:\t" << vote;
break;
case 2:
cout << "# of votes for candidate B:\t" << vote;
break;
case 3:
cout << "# of votes for candidate C:\t" << vote;
break;
default:
cout << "# of spoilt votes:\t" << spoiltvotes;
break;
}
}
return 0;
}
There is an obvious issue to your code.
When you enter your for loop : ‘for(i = 0; i <= ev; i++)’ you get to the ‘cin>>vote;’ When you get the vote if ‘vote<=5’ the loop with go on forever due to the while loop. Once you enter the while loop VOTE NEVER CHANGES. So, if the while loop condition is fulfilled, it will always be true since(again) vote doesn’t change.
Fred Larson said what I am saying essentially.
I am new to stack overflow so anything you think I should be doing, please tell me.
Others have already commented on what's the problem with your program, the while loop would never break since vote is never getting updated and if the input value in vote is <=5, it shall remain to be so and end up being an infinite while loop.
A while loop within a for loop is usually not something you'd want and should look hard at the code and see if that's what you really want. If not, refactor it out to stick with either one of them, not both.
Your problem appears to be in a similar vein. From your program, it seems that you want to read in the votes polled at the 5 voting stations and then count the number of votes that each candidate received (or went waste).
If you go the for loop route, you just need to iterate over the loop, read in the number of votes (alongwith input validations), do the switch case and then move on to the next iteration of the for loop.
If you go the while loop route, then just have a while loop to read in five votes, something like
while(std::cin>>vote) {
switch(...
and do pretty much the same stuff.
Also, global variables are (again) usually a bad idea, especially if they are non-const. Move them into your main().
Also, do take care that a break statement only breaks the inner-most loop. So, doing something like
while(true) {
int x = 1;
switch(x) {
case 1:
break;
}
}
will not break the while loop,.
Related
I have a do while loop which consists of two switch statements, some output code and some nested while loops to check for input errors. The thing is I want to break the switch statement when the user inputs 'Q' for quit and skip the rest of the code. So I've essentially got two problems.
If i use a do while, then it turns into being a return 0 and a boolean flag while(true) which logically goes against itself.
if i drop the do while and only use return 0, the code can't be executed multiple times.
I've come to terms with this being a flow problem rather than a syntax problem and was wondering how I should structure the flow to make it "clean code".
A quick example:
do {
char answer;
cout << "Type answer: ";
cin >> answer;
switch (answer) {
case A:
cout << "hello";
break;
case B:
cout << "more weird output";
break;
case Q:
cout << "Goodbye";
return 0;
}
cout << "more useless output that I want to skip";
cout << "how does this even work";
} while (run);
Here I've a return 0 which completely negates the need for a while(run) flag. This is bad coding practice I've been told, so I was wondering how one would go about structuring this in a good manner?
Here I think i fixed the code. Make sure you are typing a capital Q not lowercase. Also you forgot ' ' around your chars. Your logic was right - just small errors :) Goodluck!
#include <iostream>
using namespace std;
int
main ()
{
bool run = true;
do
{
char answer;
cout << "Type answer: ";
cin >> answer;
switch (answer)
{
case 'A':
cout << "hello";
break;
case 'B':
cout << "more weird output";
break;
case 'Q':
cout << "Goodbye";
return 0;
}
cout << "more useless output that I want to skip";
cout << "how does this even work";
}while (run);
return 0;
}
I've written a program for my C++ class and I ran into a little problem which I'm not quite sure how to solve. Some of you may be familiar with this textbook exercise as I've seen questions asked about it on the site before, but I was unable to find any simple fix.
I have to create a class which is used to store information about a pizza. I've got the program written and functional, but I need the class call to loop through a series of iterations based on the user's input. I know that this can be achieved using vectors, something we haven't hit yet in the semester, but will get to soon enough I'm sure. Is there a way to do this without vectors?
Here's the class.
class Pizza
{
private:
int type;
int size;
int numCheeseTopping;
int numPepperoniTopping;
bool cheeseTopping;
bool pepperoniTopping;
public:
Pizza();
int getType();
int getSize();
bool getCheese();
bool getPepperoni();
void setType(int t);
void setSize(int s);
void setCheese(bool choice, int temp);
void setPepperoni(bool choice, int temp);
void outputDescription();
double computePrice();
void outputPrice();
};
And the constructor.
Pizza::Pizza()
{
// Set initial class values
type = DEEPDISH;
size = SMALL;
cheeseTopping = false;
numCheeseTopping = 0;
pepperoniTopping = false;
numPepperoniTopping = 0;
}
Main is only two functions.
// Main function
int main()
{
// Call global functions
welcomeMsg();
buildPizza();
return 0;
}
I have a feeling that my problem lies in the buildPizza function, as it calls other functions as well as creating the objects. Here it is...
void buildPizza()
{
char pType, pSize, tempCheese, tempPepperoni;
int type = 0, size = 0, numCheeseTopping = 0, numPepperoniTopping = 0;
// Ask user what size pizza they would like.
cout << "What size pizza would you like?" << endl;
cout << "\tS: Small" << endl;
cout << "\tM: Medium" << endl;
cout << "\tL: Large" << endl;
cout << "Size: ";
cin >> pSize;
// Determine which size the user input and convert the
// result.
switch (pSize)
{
case 'S':
case 's':
size = SMALL;
break;
case 'M':
case 'm':
size = MEDIUM;
break;
case 'L':
case 'l':
size = LARGE;
break;
}
// Ask the user which type of pizza they would like.
cout << endl << "What type pizza would you like?" << endl;
cout << "\tD: Deepdish" << endl;
cout << "\tH: Hand-Tossed" << endl;
cout << "\tP: Pan" << endl;
cout << "Type: ";
cin >> pType;
// Determine which type the user input and convert the
// result.
switch (pType)
{
case 'D':
case 'd':
type = DEEPDISH;
break;
case 'H':
case 'h':
type = HANDTOSSED;
break;
case 'P':
case 'p':
type = PAN;
break;
}
// Call Pizza Class.
Pizza myPizza;
// Call Pizza Class functions.
myPizza.setSize(size);
myPizza.setType(type);
// Ask user whether they want cheese or not.
cout << endl << "Would you like cheese (y/n)? ";
cin >> tempCheese;
// If so call setCheese.
if (tempCheese == 'Y' || tempCheese == 'y')
{
cout << "How many cheese toppings would you like? ";
cin >> numCheeseTopping;
myPizza.setCheese(true, numCheeseTopping);
}
// Ask user whether they want pepperoni or not.
cout << endl << "Would you like pepperoni (y/n)? ";
cin >> tempPepperoni;
// If so call setPepperoni.
if (tempPepperoni == 'Y' || tempPepperoni == 'y')
{
cout << "How many pepperoni toppings would you like? ";
cin >> numPepperoniTopping;
myPizza.setPepperoni(true, numPepperoniTopping);
}
// Call outputDescription to give user an overview
// of their order.
cout << endl << endl;
myPizza.outputDescription();
cout << endl;
// Compute the cost of the pizza and display it.
myPizza.outputPrice();
}
Basically, I'd like the program to ask the user how many pizzas they would like to evaluate, create that many class iterations, then cycle through 'building' or 'ordering' each pizza, then display a total and return 0.
As I look at the code now I can take the last two function calls out of buildPizza and move the calls into main, but this will not solve my problem. Only an oversight I literally just noticed within the program.
Is there an easy way to create, say, 200 new objects all at once at runtime. Each one with a different name? Should I just pick a number to evaluate and force the user to enter information for that many objects? Right now, the program evaluates one pizza and quits.
I'd like something like this to happen:
User asks program to create a 5 pizza order.
Program creates 5 pizza objects.
Program iterates through each object getting and setting information for each one.
Program displays some stuff and returns 0.
Is this possible with my code, or do I need to consider a rewrite? Any guidance the community can give me will be immensely helpful.
Thanks.
Kyle
Since you cnanot use arrays or vectors, a simple for would suffice.
auto nrPizzas = getNumberOfPizzasFromUserInput();
for(int i = 0; i < nrPizzas; i++) {
auto pizza = Pizza{};
// do your stuff here.
output to the screen here();
}
You can prompt for the number of pizzas user want and then create a dynamic array of that much pizzas and then iterate through their build function or else you can make a linked-list with struct type of pizza and then rewrite the main logic. Second approach is advised if you do not want to prompt that how many pizza's the user wants to order.
This is the function in question. The variable in question is count1. Prior to return count1; the function appears to reset count1 to either 1 or 2. The result of the final cout line is n lines where n=number of tries including the correct answer. Each line outputs a number that is 1 higher than the line below until count1 = either 1 or 2. I haven't been able to establish a pattern as to which it will finally output.
The questions themselves are simply placeholders.
What on Earth is going on?
Note: I am a very new programmer, and I am aware that there are likely more efficient ways to do what I am doing that I have not learned. I'm open to suggestions, but my understanding of those suggestions will likely be hampered by my unfamiliarity with C++
int q1(int count1) //q1() is always fed a value of 1.
{
using namespace std;
if (count1 <= 3) //User gets 3 tries to answer for full credit.
{ //count1 is returned in order to determine user score.
cout << "What is 2+2 \n"; //problem appears to occur between here and the end of this if statement.
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
}
else
{
wrong(); //wrong() is a single line void function using std::cout and nothing else.
q1(++count1);
}
}
else
{
cout << "You have used all three tries. Next question. \n\n";
++count1; //count1 is incremented for an if statement in int main()
}
cout << count1 << "\n"; //This line is strictly for debugging
return count1;
}
Output of the final cout line looks along the lines of this:
5
4
3
2
Without \n
5432
EDIT:
There was an answer below that is deleted for some reason that appeared to resolve my problem.
The answer stated I should replace q1(++count1) with count1 = q1(++count1);
In my mind this shouldn't work, but in practice it seems to work. Why?
When using recursion, the first time your function runs count1 is 1 (as you said). If the user answers right, then your function will return 1, because the value of count1 never changes.
If the user answers wrong, then count1 increases by 1 and gives it's value to a new function (of the same type). Keep in mind that you pass the value of count1, that means the new function (the second q1()) will get the number 2 but will have a new variable count1. They may have the same name, but they are different variables.
There are two ways to solve your problem:
Either by using pointers, this way you pass the address of count1, and each function changes the same variable. (This is the hardest way and not the most efficient) or
Instead of making recursive calls, you can make a while like so:
int q1(int count1)
{
using namespace std;
while (count1 <= 3) //Run as long as user has chances
{
cout << "What is 2+2 \n";
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
//Using `break` you stop the running `while` so the next
//step is for the function to return
break;
}
else
{
wrong();
//By incrementing `count1` the next time the `while` runs
//if user ran out of tries it will not enter the loop, so
//it will return `count1` which would most likely be 4
count1++;
}
}
//Here the function is about to return, so you check if user won or lost
if (count1 == 4)
cout << "You have used all three tries. Next question. \n\n";
//Debug
cout << count1 << "\n";
//Return
return count1;
}
hi im trying to do a while loop, im new to programming and reading online i cant really get my head around it, i have used flag to show that the inputted name matches the name in the data file, i want to do this so that after i know it doesnt match it loops it the whole thing again, i have no clue how to implement this,
{
clrscr();
cout << "This Is The Option To Delete A Record\n";
char yesno;
char search;
char name[21];
int flag = 0;
cout << "Enter Employee Name : ";
Input(name,20);
for (int r=0;r<row;r++)
{
if( strnicmp(name, emp[r].first_name, strlen(name) ) == 0 )
{
flag = 1;
clrscr();
cout << "Employee Number - " << emp[r].employee_number << endl;
cout << "Name - " << emp[r].first_name << " " << emp[r].surname << endl;
cout << "Department Number - " << emp[r].department_number << endl;
cout << "Week Ending Date - " << emp[r].weekend << endl;
cout << "Delete This Record (Y/N)? : ";
Input(yesno);
yesno = tolower(yesno);
if ( yesno == 'y' )
{
emp[r].deleted = true;
cout << "Record Has Been Deleted";
}
else if ( yesno == 'n')
{
cout << "Record Hasn't Been Deleted";
}
}
}
if (flag == 0)
{
cout << "There Are No Matching Records" << endl;
}
pressKey();
}
It's pretty simple, so have a bunch of code you want to keep executing it while a flag is zero, so that's just
int flag = 0;
while (flag == 0)
{
// whole bunch of code
}
That's it, just replace 'whole bunch of code' with the code you've written above.
Implementing this in a while loop would look like this:
bool flag=false;
while(!flag){
...
if(<find a match>) flag=true;
}
Assuming you understand the for loop, I think you can understand the while loop quite easily based on the comparison of for and while.
See, you used a for loop:
for (int r=0;r<row;r++){
// do stuff
}
There are 3 key points here.
int r=0 This is your initial condition.
r<row This is your condition which keeps the loop running.
r++ This is what happens at the end of each iteration of loop.
To rephrase the statements above:
Considering r equals zero initially, while r is less than row, increment r.
Now we can easily see how while loop is striking us:) To implement this, consider the following while loop example:
int r=0; //(1)
while(r<row){ //(2)
//do stuff
r++; //(3)
}
See, now the 2 loops do practically the same thing.
If you want to do operations based on a flag, you can also prefer an infinite loop:
while(1==1){
if(some condition)
break;
}
as well as an infinite for loop:
for(;;){
if(if some condition)
break;
}
Again, 2 loops are practically the same.
so basically, you have a file with some data. And also, you accept some data from the user.
And then you perform a comparison between the appropriate fields of the two sets.
Why would you want to do it all over again once the entire comparison (file process) is done?
if you simply want to run an infinite loop, you can do this:
while(true)
{
//your code
}
you can do same with a for loop also. infact for loop and while loop both are same except for the syntax. i.e. an infinite for loop.
for (int r=0;r<row;r++)
{
if(r==row-1)
{
r=0;
}
}
I guess what you want to do is to, once one set of user input doesn't match the file content, you want to take another set and match it again and so on.
so you don't need an infinite or always executing loop for this.
Just make your comparison module a separate function which should accept the set of user inputs. All you do is accept user inputs and show the result. And give the user an option to re-enter inputs.
Below is simple algo for what you want.
int main()
{
char a='a';
while(a != '~')
{
TakeUserInput();
if(PerformComparison())
{
cout << "Success";
break;
}
}
}
inside TakeUserInput() you do all those cin << to set a global array or set of global variable. also, you cin << a, to terminate program at your will.
and inside PerformComparison(), you do what you have posted here in your question.
When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value?
Here is what I want to implement:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
bool tr=true;
while(tr)
{
if(n!=5)
cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
else
tr=false;
}
return 0;
}
You need to prompt the user in the while loop, so that it occurs in each iteration:
int n;
bool tr = true;
while(tr)
{
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n!=5) {
cout << "You entered " << n;
} else {
tr = false;
}
}
Just put all your code (except 'n' and 'tr' definition) in while loop as follow:
int main()
{
int n;
bool tr=true;
while(tr)
{
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
if(n!=5)
cout<<"You entered "<<n;
else
tr=false;
}
return 0;
}
The other answers all work, and there is something to be learned about improving program flow from them, but I believe the trick you're asking for is the continue keyword, which skips the remainder of this iteration of the loop.
bool tr = true;
int n;
while (tr)
{
cout << "Enter numbers...";
cin >> n;
if (n != 5)
continue;
else
tr = false;
}
EDIT Part 1: On the continue keyword.
You want to make your code as readable as possible. In this example, its use is unnecessary (as the other posters have shown); but it is the answer to the question "How do I skip the rest of processing in this iteration of my loop and continue to the next iteration?". Usually, such flow-breaking directives actually make code harder to read; but sometimes the opposite is true. Anything (or, at least, almost anything) that can be accomplished with continue or break, can be accomplished without them, so if you're going to use them, you want to have a definite reason for doing so. Usually, when I use continue, it's because I'm looping through a collection of inputs and I want to skip processing the loop whenever the input isn't in the format I'm expecting. Something like this (pseudo-code)...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
{
cout << "Bad input";
continue;
}
// Do massive block of calculating here.
}
is easier to read than this...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
cout << "Bad input";
else
{
// Do massive block of calculating here.
}
}
because the second version makes it harder to track what scope you're in, if you're looking toward the end of the massive block of calculating. In this case, I gain code readability by continue, so I use it. But simple code probably shouldn't use it. The break keyword is similar, though it's a lot easier to come up with examples where break is beneficial.
EDIT Part 2: On multiple iterations
This is just an issue of setting up the loop; there are no magic keywords here. The shortest way I can come up with, is probably something like this:
int n = 0;
int numberToTake = 10;
for ( int numbersTaken = 0; numbersTaken < numberToTake; ++numbersTaken)
{
cout << "Enter numbers...";
int n = 0;
for (cin >> n; n != 5; cin >> n)
cout << "Try again.";
// Do whatever processing on n you want to do here.
}
Though I should point out that, doing it this way, the only value you will ever get from the user will be 5, and if he inputs anything that doesn't fit in an integer, you will get unexpected behavior.
EDIT 3: After reading the comment more thoroughly, I think you're just looking for is the more traditional use of the for loop.
No need for the exra bool variable.
The idiom can be: Infinitely loop until the user enters 5:
for(;;) { // Loops infinitely
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n == 5)
break; // Exits the loop
cout << "You entered " << n; // Before the if if you want to print 5 as well
}