0

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.

Pandofla
  • 3
  • 1
  • 4
    The only way to go back "up" the code is to use a loop. I applaud you for wanting to learn C++ but I really suggest you learn C++ starting with one of the beginner books [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). C++ is a very complex and nuanced language and a lot of online resources tend to gloss over essential bits of material. – NathanOliver Dec 13 '19 at 13:31
  • don't use line numbers here. No one knows what line 45 or 60 is. If necessary put comment in the code indicating the line you're talking about. And don't put `;` after the if block like this `if () {};`. Besides, don't use `if (a == b) {}; if (a < b) {}; if (a > b) {}`. Use `if (a == b) {} else if (a < b) {} else {}` – phuclv Dec 13 '19 at 13:35
  • 2
    Instead of "if this, go back to here" or "if that, go forward to there", think "repeat these lines while this condition is true" (you're on the right track). You probably also want to read about `break` or the `do-while` form of loop. – molbdnilo Dec 13 '19 at 13:35
  • @Pandofla [here's a small example](https://onlinegdb.com/HypWIf-0B) how you could get your program running endlessly by using a loop – Turtlefight Dec 13 '19 at 13:44
  • you already have a loop in the code. Be careful with your variables. You have two different `keep`. It seems like `keep` was intended to control the loop, but as it stands now `keep` is not doing anything – 463035818_is_not_an_ai Dec 13 '19 at 13:50
  • formelyknownas_463035818, I didn't even notice that. The code seems to be running fine by some dumb luck of mine haha – Pandofla Dec 13 '19 at 14:47

2 Answers2

1

We all started writing our first C++ program at some time, so allow me to give you some additional feedback:

  • First of all, avoid writing using namespace std;
  • Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
  • Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>

int main()
{
    const int maximumPermittedBagSize = 45;
    // Loops forever, the user exits by typing anything except 'yes' laster
    while(true)
    {
        std::cout << "Please type your number here: " << std::endl;
        //Declare (and initialize!) variables just before you need them
        int bagSize = 0;
        std::cin >> bagSize;
        if (bagSize > maximumPermittedBagSize)
        {
            std::cout << "You passed the limit." << std::endl;
        }
        else if (bagSize == maximumPermittedBagSize )
        {
            std::cout << "Just enough." << std::endl;
        }
        else
        {
            std::cout << "You got space." << std::endl;
        }

        std::cout << "Do you want to try another number?" << std::endl;
        std::string inputFromUser = "";
        std::cin >> inputFromUser;
        std::cout << std::endl;
        //Leave the loop if the user does not answer yes
        if(inputFromUser != "yes")
        {
            return 0;
        }
    }
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
CharonX
  • 2,130
  • 11
  • 33
  • thank you a lot CharonX for explaining things in detail. Thank you for telling me I shouldn't use "using namespace std". About the the variable names, since they are small programs, I put small variable names, but I guess it's good practice to start from now and apply some easily readable and understood variable names – Pandofla Dec 13 '19 at 14:41
0

You can simply run a while loop and do like this:

#include <iostream>
using namespace std;

int main()
{
    const int limit = 45;
    int bag;
    string yn = "yes";
    while(yn == "yes")
    {
        cout << "Please type your number here: ";
        cin >> bag;
        if (limit < bag)
        {
            cout << "You passed the limit." << endl;
        }
        else if (limit == bag)
        {
            cout << "Just enough." << endl;
        }
        else if (limit > bag)
        {
            cout << "You got space." << endl;
        }
        cout << "Do you want to try another number?" << endl;
        cin >> yn;
        cout << endl;
    }
}
Muhammad Noman
  • 1,344
  • 1
  • 14
  • 28
  • Thank you Muhammad Noman, I really appreciate your answer. I haven't thought of your way, so I'm thankful for the feedback – Pandofla Dec 13 '19 at 14:39
  • And what about when there was an input error? `yn` won't ever get changed and you'll be stuck in a loop. You need to **check your inputs for errors**. – Lightness Races in Orbit Dec 13 '19 at 14:49