Home > Software design >  Calling while loop function in main function, and won't move past after completing loop
Calling while loop function in main function, and won't move past after completing loop

Time:07-10

So, I'm creating a program for class to take orders of cookies, and the guideline is to create separate functions. Unfortunately, when I try to get into the subsequent functions, it doesn't seem to be doing that, and I was wondering where my problem may be at? I've tried playing around with parameters and data types and seeing if that would do anything, unfortunately I have come up short.

I appreciate all your help guys.

#include <iostream>
using namespace std;
int getThinMints();
int getOreos();

int main(){
   getThinMints();
   getOreos();

    return 0;
}

int getThinMints(){
    int numThinMints;
    int min_order = 0;
    int max_order = 10;

        while ((numThinMints < 0 || numThinMints > 10))
        {
            cout << "Enter the number of Thin Mints (0-10): ";
            cin >> numThinMints;
            cin.ignore(100, '\n');
            cin.clear();
        }
}

int getOreos(){
    int numOreos;
    int min_order = 0;
    int max_order = 10;

        while ((numOreos < 0 || numOreos > 10))
        {
            cout << "Enter the number of Thin Mints (0-10): ";
            cin >> numOreos;
            cin.ignore(100, '\n');
            cin.clear();
        }
}

CodePudding user response:

You need to enter the value of a variable before you use it, not afterwards. For example

    for (;;) // loop until we break
    {
        // get the number of oreos
        cout << "Enter the number of Oreos (0-10): ";
        cin >> numOreos;
        // check the number of oreos is OK
        if (numOreos >= 0 && numOreos <= 10)
            break; // quit the loop if it is
        // ignore any extraneous input and try again
        cin.ignore(100, '\n');
        cin.clear();
    }

See that the test on the number of Oreos happens after the user has input a value, not before.

In your code with the while loop you were checking the value of numOreos when it had not yet been given a value. C programs are sequences of instructions and the order things happen is important. They are not declarations of intent where you just say 'I want the variable to be within these values' and leave it up the computer to figure it out.

  • Related