vendredi 13 décembre 2019

How do I execute previously executed lines of code in C++

I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:

#include <iostream>

using namespace std;

int main()
{
    const int limit = 45;
    int bag;
    cout << "Please type your number here: ";
    cin >> bag;
    string yn;
    int keep = 0;
    if (limit < bag)
    {
        cout << "You passed the limit." << endl;
    };
    if (limit == bag)
    {
        cout << "Just enough." << endl;
    };
    if (limit > bag)
    {
        cout << "You got space." << endl;
    };
    ++keep;
    while(keep > 0)
    {
        int keep = 0;
        cout << "Do you want to try another number?" << endl;
        cin >> yn;
        cout << endl;
        if(yn == "yes")
        {
            int bag = 0;
            cout << "Please type your number here: ";
            cin >> bag;
            if (limit < bag)
            {
                cout << "You passed the limit." << endl;
            };
            if (limit == bag)
            {
                cout << "Just enough." << endl;
            };
            if (limit > bag)
            {
                cout << "You got space." << endl;
            };
        }
        else
        {
            return 0;
        }
    }
}

I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60). I would appreciate it if you thought of another way to solve this problem and posted your code below. Thank you for your reply.

Aucun commentaire:

Enregistrer un commentaire