While loop creating infinite loop - c++

So I'm creating a program for a C++ class, and I created a while loop to stop invalid inputs.
Every time I do test it with an invalid input it goes into an infinite loop. I'm new to coding, so I really don't know how to fix it.
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
while (pkgweight > 0 || pkgweight < 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
}
cout << "Enter miles shipping (Max: 3500)" << endl;
cin >> distance;
while (distance > 0 || distance < 3500)
{
cout << "Shipping distance out of range." << endl;
cout << "Program terminating.\n" << endl;
}

If nothing changes inside that loop, the exit condition will never be tripped.
Maybe you mean:
int pkgweight = 0;
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
if (pkgweight < 0 || pkgweight > 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
}
You'll want to use while for situations where you want to loop until some condition is met. if is like a non-looping while.
While it's great that you're learning and it's understood you're going to make mistakes, slipping up on something this fundamental is usually a sign you don't have a good reference to work from. Get yourself a solid C++ reference book and refer to it often if you're ever stumped about something. This is essential for learning properly, not just picking up bits and pieces here and there and trying to intuit the gaps. Many parts of C++ will not make sense, they are artifacts of design decisions decades old and the influence of other programming languages you've never heard of. You need a proper foundation.

If you want the user to be able to fix an incorrectly entered input, you would want:
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
while (pkgweight > 0 || pkgweight < 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
}
That way, if the user enters a number which is outside of the valid range, they will be prompted to enter a new number. If the new value is within the range, the loop will exit.
The problem with your current program is that a while loop will execute "while" the condition it checks for is true. In your current program, once pkgweight is set, it stays the same value. This means that if the loop is entered because the condition it checks for is true, that condition will never change (allowing the loop to exit), and your error message will be printed indefinitely.

Looking at your code, it seems like you want to kill the program if the input is wrong. You could consider terminating the function. Is this all in main()? If it is not in an external function, just do return -1. I know this is probably bad programming practice, but hey, it works specifically for this!
By the way, your conditional said > 0 and < 1800, which means the program will terminate if the variables distance and pkgweight are in the specified range.
Here is my working snippet without these errors, tested on onlineGDB.
#include <iostream>
using namespace std;
int main ()
{
int pkgweight, distance;
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
while (pkgweight < 0 || pkgweight > 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
return -1;
}
cout << "Enter miles shipping (Max: 3500)" << endl;
cin >> distance;
while (distance < 0 || distance > 3500)
{
cout << "Shipping distance out of range." << endl;
cout << "Program terminating.\n" << endl;
return -1;
}
return 0;
}
Of course, instead of switching the less-than and greater-than, you could always wrap the conditional in a not operator.

Related

Endless loop in c++

I am currently learning c++ and I have come to a strange behavior at my code:
#include<iostream>
using namespace std;
int main(){
int input;
int counter = 0;
while (input != 0 && counter <= 100){
cout << "-----------\n";
cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
cin >> input;
cout << "The number: " << input << "\n";
counter++;
}
return 0;
}
This Program itself works fine, but when I am typing a number as input, which is at least the maximum of the integer datatype + 1, then this loop will be endless (I programmed a stop after 100 loops) and I cannot really explain this to me. In other languages the program just crashes or gives out an error, because the allocated storage is just not high enough for the data typed in, what is logic and I understand that, but why do the loop gets endless here, that does not make any sense, because I cannot do any inputs after this happens, it just keeps doing the loop with the value (integer maxnumber, in my book stands, that the maxnumber can vary from system to system, so I do not type my number) endlessely and I cannot do anything, but watch my console getting flooded with the same 4 lines.
I would really appreciate, if somebody could explain this phenomena to me, I mean it is not crucial, but it catched my interest anyways.
Your input variable needs to be initialized because you check its value in the while (input != 0 && counter <= 100){ before assigning the input value.
Undefined Behaviour is typical in C++ when exceeding data type limits. These are some common UB.
This post contains the "solution" to your problem
How about the following? Is this what you want?
#include<iostream>
using namespace std;
int main(){
int input;
int counter = 0;
cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
cin >> input;
cout << "The number: " << input << "\n";
while (input != 0 && counter <= 100){
cout << "Please enter the next number: ";
cin >> input;
cout << "The number: " << input << "\n";
counter++;
}
}

Inner while loop iteration with outer loop

I have a simple nested while loop situation but I'm not sure how to increment numGuesses inside the second loop to escape the first loop once it is no longer less than 5.
while(numGuesses<5){
while(!correct){
cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
numGuesses++;
cin >> guess;
if(guess<number){
cin.clear(); //clears input stream
cin.ignore(256, '\n');
cout << "\nSorry, your guess is too low";
}
else if (guess>number){
cout << "\nSorry, your guess is too high";
}
else{
cout << "\nYou guessed right, you win!";
correct = !correct;
}
}
}
cout << "Sorry, you lost. The number is: " << number;
Each time the inner while loop iterates I would like numGuesses to increase but I'm guessing its not in its scope?
You should just use one while loop! After all, the thing you're looping over is prompting for a guess. There's no need for a second layer of looping inside that. Think about when you want to stop asking for a guess -- when the guesses get to 5 or when they get it correct. So when do you want to keep asking for a guess? When the guesses are less than 5 and they have not got it correct. Also, you want to say whether they lost after the end of the loop depending on the value of correct.
while(numGuesses<5 && !correct) {
cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
numGuesses++;
cin >> guess;
if(guess<number){
cin.clear(); //clears input stream
cin.ignore(256, '\n');
cout << "\nSorry, your guess is too low";
}
else if (guess>number){
cout << "\nSorry, your guess is too high";
}
else{
cout << "\nYou guessed right, you win!";
correct = !correct;
}
}
if (!correct) { // loop stopped before they got it correct
cout << "Sorry, you lost. The number is: " << number;
}
You'll also want "\n"s or std::endls at the end of your print statements, otherwise your code will print everything on one line.
You don't need 2 whiles...
while(numGuesses < 5 && !correct)
{
// your logic here
}
After that you can check either the variable correct or numGuesses. For example:
if(!correct)
// your code

program to find the minimum of a set of numbers using while loop in c++

I am new to c++ and I have been having a hard time understanding the following program. it looks so simple and so it made me feel like I am wrong about everything I have learn so far in c++.
int number = 0;
int min = 0;
cout << "enter (-1) to stop" << endl;
while( number != -1)
{
cout << "Enter an integer:";
cin >> number ;
if (number < min)
min = number;
}
cout << "your minimum number is: " << min << endl;
what I am mostly confused about is the if statement. "min" has only been initialized as equal to zero so the entire if statement does not make sense to me. there is nothing that really defines "min" in the program in my opinion.
Any contribution is much appreciated. thank you!
the program does work fine. And, indeed it does find the minimum of a set of numbers that a user enters. I just do not understand how that happens
On each iteration of the loop a new number is read in using cin. Because number is a signed integer it is possible that it is less than min in which case the if will pass. It is strange that min starts at 0 but the if statement is not redundant.
Initialize min with first number entered.
cout << "enter (-1) to stop" << endl;
cout << "Enter an integer:";
cin >> number ;
min = number;
while( number != -1)
{
cout << "Enter an integer:";
cin >> number ;
if (number < min)
min = number;
}

Do-while loop with if-statement in body which only prints a message after one iteration?

This probably requires only basic problem solving skills but I am trying to create a very short way to: ask the user for input and only say that the input is not legit after it did not pass the condition check at least once. A do while loop seemed to fit..
How I implemented it below will always create a problem in that 1 specific number creates a bug, namely if the user enters 0 you don't get the message while you should, I could change it to a very special number but still this front-end bug would remain. I come from a Java background in which null is the default value making this easy, but because of efficiency reasons this seems not to be the case in c++. I could declare a bool but that seems like too much of a workaround.
Here is the code I have now:
int birthYear = 0;
do {
if (birthYear != 0) cout << "Your input " << birthYear << " is not a legit birthday";
cout << "What is the year you were born?: "; cin >> birthYear;
} while (birthYear < 1900 || birthYear > 2100);
This is a classic example where neither the while nor the do/while loop is an exact fit, because you need to do something before and after checking the loop condition.
Rewrite your loop as a "forever" loop with a break in the middle:
for (;;) {
cout << "What is the year you were born?: ";
cin >> birthYear;
if (birthYear >= 1900 && birthYear <= 2100) {
break;
}
cout << "Your input " << birthYear << " is not a legit birthday";
}
You could try adding a flag:
int birthYear = 0;
bool birthYearInvalid = false;
do {
if (birthYearInvalid) cout << "Your input " << birthYear << " is not a legit birthday";
cout << "What is the year you were born?: "; cin >> birthYear;
birthYearInvalid = (birthYear < 1900 || birthYear > 2100);
} while (birthYearInvalid);
One extra variable.. could be good (more self documentation)

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