problems with switch statement involving functions [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This program is not prompting me for input. I need help with defining, and calling functions properly. menu() is supposed to display a string of text, and ask the user to select a number 1-4, and if the user enters a number outside of that it will ask the user to enter an appropriate number until 1-4 is entered. The value of menu() will be stored in a variable 'choice' and be used in a switch statement.
Inside of the switch statement the corresponding choice functions[getSum(), getFactor(), getExpo(), and exit()] are called. They each need to ask the user for an integer, and perform some arithmetic, and return some output text to the user with the calculated value.
All of this is inside of a do while loop repeating this process, until the user chooses the option 4 to quit the program, where the exit() function will return a string exit message to the user and then the program will terminate.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu();
long int getSum();
long int getFactor();
long int getExpo();
string exit();
int main()
{
const int SUM = 1, // Summation choice
FACTOR = 2, // Factorial choice
EXPO = 3, // Exponential choice
QUIT = 4; // Exit choice
int choice; // Numerical menu choice
long int sums, facts, expos;
string quits;
// Force the console to print standard notation
cout << fixed << setprecision(0);
// Do-While loop controlled by the users choices
do
{
choice = menu();
switch (choice) // Start switch option
{
case SUM: // 1st choice
sums = getSum();
break;
case FACTOR: // 2nd choice
facts = getFactor();
break;
case EXPO: // 3rd choice
expos = getExpo();
break;
case QUIT: // 4th choice
quits = exit();
break;
default: // Default choice
// Error message for input outside domain
cout << "Please make a selection of either 1,2,3 or 4.\n\n";
cin >> choice; // Repeat attempt to gather input from user
}
}
while (menu() != QUIT);
return 0;
}
int menu()
{
int choice;
cout << "\n\t\tMathematical Menu\n" // Header
<< "1) Summation\n" // 1st choice
<< "2) Factorial\n" // 2nd choice
<< "3) Exponential\n" // 3rd choice
<< "4) Exit Program\n\n" // 4th choice
<< "Please make a selection\n" // Ask user for imput choice
<< "of either 1,2,3 or 4.\n\n";
cin >> choice; // Gather input from user
return choice;
}
long int getSum()
{
int total = 0, userNum, counter;
// Ouput statement to user
cout << "Please enter a positive integer value greater than 0 \n"
<< "and less than 10,000,000.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
// Compare input to domain
if (userNum < 0 || userNum > 10000000)
{
// Error message for input outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic summation
for (counter = 1; counter <= userNum; counter++)
{
total += counter; // Running count
}
cout << "The total value for the added numbers 1 to \n"
<< userNum << " is:\n"<<total;
return total;
}
long int getFactor()
{
int total, userNum, counter;
total = 1;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic factorial
for (counter = 1; counter <= userNum; counter++)
{
total *= counter; // Running count
}
// Display arithmetic output to user
cout << "The total value for the multiplied numbers 1 to \n"
<< userNum << " is:\n";
return total;
}
long int getExpo()
{
int total, userNum, counter;
total = 0;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic exponential
for (counter = 1; counter <= userNum; counter++)
{
total = pow(2.0, userNum); // Running count
}
// Display arithmetic output to user
cout << "The total value for the exponential function is \n";
return total;
}
string exit()
{
// Exit message
return "Don't be gone for too long...\n";
}`

Do not call menu() more than once: it will prompt the user twice.
Do not return anything from a function that does all the work anyway. Make it
void getExpo(){ ...; return; }
Call:
getExpo();

Related

Why is my variable value not resetting to 0?

Working on a C++ program that calculates the value of pi. I can run it once correctly and it will output the desired value. But the part of the program where it asks the user if they want to run again, that value of pi will not be correct according to the formula. I can't seem to figure out where I am going wrong here.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int seqNum; // Declares variable for user input
char response; // Will hold char if user wants to rerun the program or not.
// Welcome Message and prompts user to input an integer
cout <<"Welcome to the Calculating Pi Program!\n";
cout <<"Please enter an integer greater than 0: \n";
// Assigns user input to the seqNum variable
cin >> seqNum;
// While loop to validate user input
while (seqNum < 1)
{
cout <<"ERROR: You must enter an greater than 0\n";
cout <<"Please enter an integer greater than 0: \n";
cin >> seqNum;
}
double pi = 0;
for (int i=0; i <= seqNum; i++)
{
double sum = 1.0/(2*i+1);
if (i % 2 == 0)
pi += sum;
else
pi -= sum;
if (i == seqNum)
{
pi *= 4;
cout << fixed << setprecision(50) << pi << endl;
pi = 0;
i = 0;
cout << "Do you want to run again (Y/N):";
cin >> response;
if (response == 'Y' || response == 'y')
{
cout << "Please enter an integer greater than 0: \n";
cin >> seqNum;
}
else
return 0;
}
}
return 0;
}
You're not resetting your loop index. If I understand correctly your intent, you should add i = -1; in the true part of if (response == 'Y' || response == 'y'). The comment by user4581301 is also good advice.
When your calculations run again in your for loop, the index starts at 1 instead of 0 because in for loops the (;;i++) happens after the code block, every time it loops. A super easy fix is to just assign i=-1; when you reset (I wouldn't recommend this dirty fix, it was to demonstrate the issue).

How to make the program take in a list of integers?

I just started learning c++ and is learning topics related to cin, cin.get. In one of my assignments, the requirement is this:
Write a program that reads in a list of integer numbers and prints the largest and the
smallest number.
You can assume that the the user's input is always valid.
You can assume that the numbers in the list are separated by one space character and
that the character following the last number in the list is the newline character .
Implement a loop in which the above actions are repeated until the user requests to quit.
The code I came up with is:
using namespace std;
int main()
{
char ch = ' ';
int max=0;
do
{
int x;
cin >> x;
ch = cin.get();
if (max = 0) { max = x; };
if (x > max) { max = x; };
} while (ch != '\n');
cout << "maximum=" << max << endl;
return 0;
}
I was expecting to have this return the maximum of the numbers in the list. But it turned out only to return the last integer in the list.
I also don't quite get why the line:
cin >> x;
ch = cin.get();
makes the program able to accept a list of numbers. Isn't cin suppose to ask the user to input some stuff, as well as cin.get? In another word, shouldn't the user encounter input two times? But why is it when I run I am only asked to input once?
After some adjustment using the comments in this post, I was able to come up with the code as such:
int main()
{
cout << "Enter the list of integer numbers: ";
char ch = ' ';
int max=0;
int min = 0;
do
{
int x;
cin >> x;
ch = cin.get();
if (max == 0) { max = x; };
if (x > max) { max = x; };
if (min == 0) { min = x; };
if (x < min) { min = x; };
} while (ch != '\n');
cout << "maximum=" << max << endl;
cout << "minimum=" << min << endl;
return 0;
My final question is: How can I satisfy the requirement of this assignment "Implement a loop in which the above actions are repeated until the user requests to quit."
Your initial problem lies with the code:
if (max = 0) { max = x; };
The single = is assignment, not comparison. What is does is set max to zero, then use that zero as a truth value, which always equates to false.
Hence the effect is that max will be set to zero, and the body of the if will never be executed.
You need to use == for comparison.
In terms of looping until user indicates they want to quit, you can use the fact that invalid input can be detected with the >> extraction operator.
As an aside, since extraction of an integer first skips white-space, you don't have to worry about handling spaces and newlines at all, they'll naturally be skipped as part of the "get next integer" operation.
By way of example, the following complete program will exit when you enter q (or any invalid number for that matter, though if you enter 47q, it will handle the 47 first before exiting on the q):
#include <iostream>
int main () {
int inVal;
while (true) {
std::cout << "Enter number (q to quit): ";
if (! (std::cin >> inVal)) break;
std::cout << inVal << '\n';
}
std::cout << "Done\n";
}
A sample run follows:
Enter number (q to quit): 1
1
Enter number (q to quit): 2
2
Enter number (q to quit): 3
3
Enter number (q to quit): 55
55
Enter number (q to quit): 42
42
Enter number (q to quit): q
Done
So you can use that to detect non-numeric input and act accordingly:
#include <iostream>
int main () {
int inVal, maxVal, minVal, firstTime = true;
while (true) {
std::cout << "Enter number (q to quit): ";
if (! (std::cin >> inVal)) break;
if (firstTime) {
firstTime = false;
minVal = maxVal = inVal;
} else {
if (inVal > maxVal) {
maxVal = inVal;
}
if (inVal < minVal) {
minVal = inVal;
}
}
}
if (firstTime) {
std::cout << "*** You didn't enter any numbers.\n";
} else {
std::cout << "*** Minimum was " << minVal
<< ", maximum was " << maxVal << ".\n";
}
}
Some sample runs of that:
pax:~> ./testprog
Enter number (q to quit): q
*** You didn't enter any numbers.
pax:~> ./testprog
Enter number (q to quit): 1
Enter number (q to quit): q
*** Minimum was 1, maximum was 1.
pax:~> ./testprog
Enter number (q to quit): 9
Enter number (q to quit): 8
Enter number (q to quit): -3
Enter number (q to quit): 7
Enter number (q to quit): 5
Enter number (q to quit): 42
Enter number (q to quit): q
*** Minimum was -3, maximum was 42.
I'm assuming here the allowed assumption that the user input is always valid applies to the allowed characters being input (such as "no 47q allowed"), and that, if the marker complains that you're meant to stop on the first newline, you can argue that any number after that newline constitutes invalid data, and is therefore an invalid test case.
In the real world, you'd write your code robustly enough to handle edge cases like that but I suspect it's not necessary for educational work (even if it may earn you some extra marks).

Trouble with a beginner coding challenge

Write a program that continues to ask the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.
★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.
★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)
I got most of the program to work. I have it to a point where it asks for a number starting at 0 and going up, it gives the user the patient message after 10 tries, and exits the program if they enter the number they are not supposed to. However if the user inputs the number above what it tells you not to enter, the program exits with no message.
I do not really know what to search to fix this issue. I have however tried to move some things around, and got rid of some redundant variables.
Any hints would be appreciated, please do not give me the answer up front! Here's what I have so far.
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 10; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then "<< InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!\n";
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
} while (UserNum != InputNum);
return 0;
}
your problem is in do while loop condition
statements are executed first and condition are checked later
for example
InputNum is initialized as 1
so if you enter 2 as input for UserNum , in the else if condition ,InputNum will be incremented to 2
when this condition is evaluated
while (UserNum != InputNum)
it will be false as 2==2
loop breaks
solution
change PATIENCE = 11 and use
while (1)
// this will run infinitely but it will break after 10 iteration or when u press the same number which u shouldn't
instead of
while (UserNum != InputNum)
the full program
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 11; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then " << InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!\n";
break;
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
} while (1);
system("pause");
return 0;
}
Hey try this program it does exactly what you want.
#include <iostream>
int main ()
{
int GUESS = -1; //loop variable
const int PATIENCE = 10; // constant for message at 10 tries
int InputNum; // input from user
std::cout << "PATIENCE Test" << "!\n";
do
{
GUESS++;
// asks for player's input
std::cout << "Enter any number other than " << GUESS << ": ";
std::cin >> InputNum;
// exits program if user inputs the number displayed
if (GUESS == InputNum)
{
std::
cout << "Hey! you weren't supposed to enter " << GUESS << "!\n";
break;
}
if (GUESS == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
}
while (GUESS != InputNum);
return 0;
}

How to evaluate number greater than and less than in the same while loop?

// DiceRollProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int diceRoll(int max); // function definition
int getValidInteger();// function definition
int main() {
srand(time(0)); // seed the random number generator
int exitProgram = 0;
int guess, rollValue;
int maxRollValue = 6;
cout << "Hello! Let's play a dice game. Let me do the first roll for you.\n" << endl;
rollValue = diceRoll(maxRollValue);
cout << "In this roll, you got: " << rollValue << "\n" << endl;
do {
rollValue = diceRoll(maxRollValue);
cout << "What's your guess for the next roll? Enter an integer between 1 and " << maxRollValue << ": ";
guess = getValidInteger();
// TODO: Validate input
if (guess > rollValue)
{
cout << "The guess was too high!";
}
if (guess < rollValue)
{
cout << "The guess was too low!";
}
if (guess == rollValue)
{
cout << "You guessed correctly, congrats!";
}
cout << "In this roll, you got: " << rollValue << "\n" << endl;
// TODO: Evaluate result
cout << "Enter 1 to exit or any other integer to continue rolling ";
exitProgram = getValidInteger();
cout << "\n";
if (exitProgram == 1)
{
cout << "Sorry to see you go. Have a wonderful day!\n" << endl;
}
} while (exitProgram != 1);
return 0;
}
// Roll the die
int diceRoll(int max) {
int rollValue;
rollValue = (rand() % max) + 1;
return rollValue;
}
// Check if user entered an integer
int getValidInteger() {
int userInput;
cin >> userInput;
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Please enter an Integer only ";
cin >> userInput;
cout << "\n";
}
return userInput;
}
I have a dice roll guessing game, I'm trying to evaluate the users input, to make sure that they can't enter a number less than 1 and greater than 6, unfortunately, with just my if statements, they can still enter these numbers, although a string is displayed that the input is not valid, I want to make a while loop that keeps asking them to enter a valid number equal or greater than 1 and equal to and less than 6, if the user keeps inputting an incorrect number, the while loop will keep asking them for a valid number, until they do enter one, which will then run the program as normally.
First of all, inside the while loop you have dead code.
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
Within the loop body, the first if is always true and the second one is always false. You should enter in a loop when the user writes an invalid input. This happens when (userInput < 1 or userInput > 6)
After the evaluation of the while's condition, you should ask the user to write input
do {
cout << "Please enter an Integer only ";
cin >> userInput;
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}while(userInput < 1 || userInput > 6);
So your condition that will keep you in the while loop is if the person guesses too high or too low. Inside the while loop I would add the updating condition or statement that you would like to repeat. So in your case, "your guess is too high" or " your guess is too low" and ask for their input again. I am not a pro but I would keep it simple by constructing 2 while loops, one for too high and one for too low just like your if statements. literally you can just change your first two if statements to while loops and adding an few extra lines of cout to ask the person to guess again and validate their input. I hope this helped.
from what I've understood you are looking for something like this:
int main (){
int my_magic_number=(rand()%6)+1,usernumber=-1;
bool state;
while (usernumber!=my_magic_number){
cin>>usernumber;
state = (usernumber<1||usernumber>6);
while (state) {
cout<<"You entered a number outside the range [1,6] please try again\n";}
cin>>usernumber;
state = (usernumber<1||usernumber>6);
}
if (usernumber!=my_magic_number) {/* do whatever you want */}
} //while loop
} // main

Program that finds Highest, Lowest, and Average of 5 number from an Array

My homework is to write a program that finds the highest, lowest, and average of 5 numbers in an Array that the user inputs. Here is my problem, the user does not have to enter all 5 numbers. But has to enter at least 2 numbers minimum.
I have the whole program done already I am having a problem with the beginning, below is my code where I am having a problem:
// Ask for name and explain program
cout << "Please enter your name: ";
cin >> name;
cout << endl;
cout << "Hi " << name << ", please enter up to 5 whole numbers." << endl;
cout << "I will find the HIGHEST, LOWEST, and AVERAGE number." << endl;
// Loop through users input
for (int i = 0; i < SIZE; i++)
{
cout << "Enter number " << (i + 1) << " : ";
cin >> number[i];
// Validate that the user has entered atleast 2 numbers
if (i >= 1 && i < 4)
{
cout << "Do you wish to enter another number (Y/N)? : ";
cin >> continue_game;
// Validate that the user only enters Y/N
while (continue_game != 'Y' && continue_game != 'y' && continue_game != 'N' && continue_game != 'n')
{
cout << "Please type in (Y/N): ";
cin >> continue_game;
}
// What happens if user chooses NO
if (continue_game == 'N' || continue_game == 'n')
{
i = 5;
}
// What happens if user chooses YES
else if (continue_game == 'Y' || continue_game == 'y')
{
i = i;
}
}
}
PROBLEM: If the user presses no after the 2nd number the remaining elements get a number asigned to them like : -8251616. Is there any way to make sure that the elements get assigned a zero or stay blank please help its due tomorrow and I can not figure it out.
SIZE = 5
Don't set i = 5 when the user says no. Just end the loop with a break; statement.
Also, the i = i; statement in the yes case is useless.
When you're getting the highest, lowest, and average values, make sure you only look at the values from 0 to i-1, so you don't access the uninitialized elemends of the array.
If you really want zeros you need to fill array with zeros:
int number[5] = {};
or
int number[5];
for (int i = 0; i < 5; ++i) {
number[i] = 0;
}
However this will give wrong output if the user enter less than 5 numbers. What you should do is to count how many numbers user entered and then use values from 0 to count - 1.
Advice, use break; instead of i = 5;.