Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop creating infinite loop

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;
    }
like image 421
Jessica Alvarado Avatar asked Feb 01 '26 10:02

Jessica Alvarado


1 Answers

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.

like image 144
tadman Avatar answered Feb 04 '26 00:02

tadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!