Search code examples
c++while-loopinfinite-loop

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;
    }

Solution

  • 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.