Why won't my do-while loop continue looping? - c++

I'm working on creating a menu with error checking and this is what I've come up with, but I can't seem to get it to work.
#include <iostream>
using namespace std;
int main()
{
char option; // user's entered option will be saved in this variable
int error1 = 0;
//Displaying Options for the menu
cout << "There are three packages available." << endl;
cout << "Monthly Price - Price per MB for overages (excluding C)" << endl;
cout << "A) $15 - $.06 for each MB after 200 MB." << endl;
cout << "B) $25 - $.02 for each MB after 2,000 MB ( approx. 2 GB)." << endl;
cout << "C) $50 - Unlimited data." << endl;
do //do-while loop starts here
{
//Prompting user to enter an option according to menu
cout << "Please enter which plan you currently have : ";
cin >> option; // taking option value as input and saving in variable "option"
if(option == 'A' || option == 'a') // Checking if user selected option 1
{
cout << "You chose a" << endl;
error1 = 1;
}
else if(option == 'B' || option == 'b') // Checking if user selected option 2
{
cout << "You chose b" << endl;
error1 = 1;
}
else if(option == 'C' || option == 'c') // Checking if user selected option 3
{
cout << "You chose c" << endl;
error1 = 1;
}
else //if user has entered invalid choice
{
//Displaying error message
error1 = 0;
cout << "Invalid Option entered";
}
}
while(error1 = 0); //condition of do-while loop
return 0;
}
When typing in an incorrect value, the output will be Invalid Option entered; however, it won't loop back to the beginning and prompt the user for input again.
Why is it doing this?

Change
while(error1 = 0); //condition of do-while loop
into this
while(error1 == 0); //condition of do-while loop
in the first option you just assign 0 to error1 and then error1 is being tested as boolean which means 0 is FALSE and non-0 is TRUE. So sonce the condition in the while is evaluated as FALSE, the loop ends.

You are assigning 0 to error1 inside the while, which is always false, so the loop will not repeat. Change while(error1=0); to while(error1==0);

Just as complement: consider invert the expression thus:
while (0 = error1);
In this way the compiler will stop you if you forget the additional = or confound the assignment with the equal operator

Related

Non integer input causes infinite loop

i created a code for my final project. where in the start the user is asked what calculator to use its either the average calculator or simple calculator. but if the user accidentally entered a non integer it causes in infinite error loop but if its an integer that is not in the choices it works because i created a while loop. i need help what do i need to do to prevent the infinite loop.
cout << 1. average calculator: << endl;
cout << 2. simple calculator: << endl;
cout << Enter the Number << endl;
cin >> choice;
while (choice > 2 || choice <= 1)
{
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
cin >> choice;
}
You need to clear the input buffer. Also the condition in this if statement is incorrect
while (choice > 2 || choice <= 1)
It seems you mean
while (choice > 2 || choice < 1)
The while loop can be rewritten as do-while loop the following way
#include <limits>
//...
bool input_error = false;
do
{
input_error = false;
if ( not ( std::cin >> choice ) )
{
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
input_error = true;
}
else if ( choice < 1 || choice > 2 )
{
input_error = true;
}
if ( input_error )
{
std::cout << "Error! Please choose a number between 1 and 2 only.\n";
std::cout << "Enter the number again: ";
}
} while ( input_error );
Instead of using a while loop, you could use a switch like this
switch(choice //this is the input)
{
case 1:
//the stuff you want to do
break; //always a break
case 2:
//more stuff
break;
default:
//throwing a error
std::cout << "Error, please pick a number between 1 and 2\n";
}
and if you want to repeat until you pick the right number, you could put the switch inside a do while loop like this
do
{
switch(choice)
{
//the stuff
}
}while(choice > 2 || choice < 1);
let's hope this will work
have a nice day.
cout << "1. average calculator:" << endl;
cout << "2. simple calculator:" << endl;
cout << "Enter the Number" << endl;
string stringInput;
getline(cin, stringInput);
int choice = atoi(stringInput.c_str());
while(choice < 1 || choice > 2) {
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
getline(cin, stringInput);
choice = atoi(stringInput.c_str());
}
You should read whole line, store it in string, and then convert that string to integer using atoi(). atoi() expects c-string to be passed so std::string should be converted to c-string. It is done by stringInput.c_str().
I changed while condition(choice > 2 || choice <= 1) to (choice < 1 || choice > 2) because it says to enter number between 1 and 2, but with your condition entering number 1 would print "Error! Please choose a number between 1 and 2 only.".

Trying to condition my do-while to stop exiting program in terminal. Menu does not loop in while as desired with current statements

I have an issue with my do-while loop where it will exit the program no matter the input or my statements in while.
I'VE TRIED CHANGING
while(menureturn > '4' || menuselect < '1');"
TO
while(menureturn > '4' && menuselect < '1');
HERE IS THE SOURCE CODE MY PROJECT
#include <iostream>
#include <string>
using namespace std;
int choice, menuselect;
char menureturn;
int menu() {
cout << "1. Math Menu" << endl;
cout << "2. Currency Conversion" << endl;
cout << "3. Cryto Currencies" << endl;
cout << "4. Display Time Zone selection" << endl;
cout << ":" << endl;
cin >> menuselect;
return menuselect;
}
int main()
{
do {
menu();
} while(menureturn > '4' && menuselect < '1');
return 0;
}
MY OUTPUT
1. Math Menu
2. Currency Conversion
3. Cryto Currencies
4. Display Time Zone selection
:
6
C:\Users\Gage\source\repos\Menu\Debug\Menu.exe (process 35580) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
Your problem was that you were comparing if an int number, was the same as char when you put ' ' around your numbers.
} while(menureturn > '4' && menuselect < '1');
And you did not assign menureturn to any value which just leaves it being null and doesn't contain a value, and therefore should not be used in a condition.
So this can be fixed very simply by first not comparing in the Do-While-Loop using a char but rather by using an int. Then we can simply just assign the menu() function to an int - since that is the return type and just compare that value
#include<iostream>
#include<string>
using namespace std;
// choice variable
int choice;
// the menu function
int menu()
{
cout << "1: Do Something" << endl;
cout << "2: Do Something" << endl;
cout << "3: Do Something" << endl;
cout << "4: Do Something" << endl;
cout << ":" << endl;
cin >> choice;
return choice;
}
int main()
{
// declare an empty int
int output;
do
{
// assigning the int to
// return value of menu()
output = menu();
} while(output > 0 && output < 5)
// Do Something Else
}
Note
using || in a condition will return as soon as one of the statements are true or false. Where as && will only return if all the statements are either true or false in the condition.
Or, are you looking for another form of answer?

How to use a (while) loop and where to place it if eligible for all code

On c++, im trying to make a program that will repeatedly accept the input of the user unless -999 is pressed. Additionally, if the input is not divisible by 5 or 20, then I asked for it to output "must enter divisible by 5 or 20." I want this to continue being done until they enter -999 but I do not know where to put my while loop or what to put if it is not entered. I also do not know where to put the "when finished enter -999 to leave" while making it eligible for all times and not just the start. Thank you!!!
#include <iostream>
using namespace std;
int main(void)
{
int amountEntered;
cout << "Please enter the amount of money you would like to dispense (must be in 20's or 5's)" << endl;
cout << "when finished, enter -999 to leave" << endl;
if (amountEntered == -999)
{
cout << "Thank you for doing business." << endl;
}
cin >> amountEntered;
if (amountEntered % 20 == 0)
{
cout << amountEntered / 20 << endl;
}
else
{
if (amountEntered % 5 == 0)
{
cout << amountEntered / 5 << endl;
}
else
{
cout << "You must enter multiples of twenty or five only!" << endl;
}
}
{
while (amountEntered != -999);
while (amountEntered % 5 == 0);
else
{
if (amountEntered % 5 != 0)
{
cout << "You must enter multiples of twenty or five only!" << endl;
}
}
while (amountEntered % 20 == 0);
}
if (amountEntered % 20 != 0);
{
cout << "You must enter a number divisible by 20 or 5!" << endl;
}
if (amountEntered = -999)
{
cout << "Thank you for doing business." << endl;
}
}
Here is some pseudocode to illustrate:
while true
get input
if input is -999 (or other conditions)
break out of loop
else
// rest of code goes here
So basically, wrap the whole thing in a while true loop and then use the conditional logic to break out of the loop when certain conditions are met.
On c++, im trying to make a program that will repeatedly accept the input of the user unless - 999 is pressed.
Additionally, if the input is not divisible by 5 or 20, then I asked for it to output "must enter divisible by 5 or 20."
#include <limits> // std::numeric_limits<>
#include <iostream>
int main()
{
for (;;) { // forever
int value;
while (std::cout << "Thou must enter a value divisible by 5 or 20. When finished enter -999 to leave.\n",
!(std::cin >> value) || value != -999 && value % 5 != 0 && value % 20 != 0)
// ^^ extraction failed or value does not conform to requirements
{
std::cerr << "Input error :(\nYou must enter a number divisible by 5 or 20.\n";
std::cin.clear(); // clear the flags that might have been set by a
// failed input operation.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ^^ discards up to the maximum value of std::streamsize characters
// until a newline character ('\n') is encountered. If we don't do that
// the next input operation will choke on the same erroneous input.
}
if (value == -999)
break;
// do sth with value
}
}
I want this to continue being done until they enter -999 but I do not know where to put my while loop or what to put if it is not entered. I also do not know where to put the "when finished enter -999 to leave" while making it eligible for all times and not just the start.
Perhaps you might want to break the problem down. Firstly, you would know that the "end condition" of this loop would be that the user keyed in -999. Hence you would want your loop to look something like
while userinput != -999
// do something here
end while loop
With that, all we need is to place the capturing of user input. One would be at the start, and one just before the while loop ends.
get userinput
while userinput != -999
// do something here
get userinput
end while loop
There are several ways to approach this problem, and that's depending on how you want to design your code. Here's my approach for this:
#include <iostream>
void Request(int& amount)
{
std::cout << "Please enter the amount of money you would like to dispense (must be in 20's or 5's)" << std::endl;
std::cout << "when finished, enter -999 to leave" << std::endl;
std::cout << ">";
std::cin >> amount;
}
int main(void)
{
int amount = 0;
for (Request(amount); amount != -999; Request(amount))
{
// Since 20 is a multiple of 5, just check if its divisble by 5 will do
if (amount % 5)
{
std::cout << "You must enter multiples of twenty or five only!" << std::endl;
continue;
}
// Otherwise print out (or do stuff here)
std::cout << amount % 5 << std::endl;
}
std::cout << "Thank you for doing business." << std::endl;
}

How could I exit from do-while loop?

I have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer

Menu Structure and Loops

I have this little program I am creating. In lamens terms, I am wanting to make a menu where a user can input his selection, it takes him to the predetermined area and after he is done it takes him back to the menu where he can make a different selection. I have gotten down where it displays when you press 1 (you will see what i mean with the code). But after it goes through what it is supposed to do, it doesn't go back to the menu it just continues on to the second option. Also say you are at the menu and you want to start with the 2nd option it just starts with the first. Can anyone please help me with this...
#include <iostream>
using namespace std;
int main()
{
int option;
cout << "Hello there...\n\nToday we are going to do a little fun project that I created.\n\n";
cin.get();
cout << "\nAs we progress throughout this program, I will explain the different things\n";
cout << "that we are going to do. We will be covering some basic C++ excersises.";
cout << "\n\nFirst and foremost we will begin by covering what I have learned so far....\n\n";
cin.get();
cout << "The first topic we will cover will include what is known as 'variables'.\n";
cout << "what are variables you ask?";
cin.get();
int var = 1;
int main=1;
do
{
cout << "\n\n\nEnter the number of one of the following and I will explain!\n";
cout << "1.integer 2.boolian 3.floats 4.doubles 5.character";
cout << "\n\n[when you are done type 'done' to continue]\n\n";
cin >> option; //this is where the user puts in his option (1,2,3,4,5,6) I have only 1 and 2 complete
if (option = 1) //starts with this regardless of input
{
cin.ignore();
cout << "\n\n\nInteger is the variable abbreviated as 'int' this allows C++ to only";
cout << "\nread whole and real numbers. C++ takes this number as stores it\n";
cout << "in a user-defined variable (you can make up what that variable is..)\n";
cin.get();
cout << "an example syntax would be:";
cout << "\n\nint var=[whole;real number]";
cin.get();
cout << "\n\nwhat this implies is that you have 'declared' to the system";
cout << "\nthat you are going to use an 'int' that you have named 'var'\n";
cout << "and in this 'var' you are going to store a real and whole number\ninside of it.";
cout << "\n\nPress any key to go back to menu";
cin.get();
}
else if (option = 2); //continues with this without going back to menu.
{
cin.ignore();
cout << "\n\n\nBoolian is the variable abbreviated as 'bool' this allows C++ to only";
cout << "\nread true or false ( 0 or 1 ). C++ takes this number as stores it\n";
cout << "in a user-defined variable (you can make up what that variable is..)\n";
cin.get();
cout << "an example syntax would be:";
cout << "\n\nbool var=[true or false]";
cin.get();
cout << "\n\nwhat this implies is that you have 'declared' to the system";
cout << "\nthat you are going to use an 'bool' variable that you have named 'var'\n";
cout << "and in this 'var' you are going to store a either a true or false\ninside of it.";
cout << "\n\nPress any key to go back to menu";
cin.get();
}
} while (var = 1);
}
The problem lies with the comparison operator
1) if (option = 1) , use if(option == 1)
2) else if (option = 2); , use else if(option == 2) , remove the semicolon
3) while(var = 1) ; , use while(var ==1 );
comparision in C++ is done with the == operator:
e.g.
if (option == 1)
if (option == 2)
while (var == 1);