Loops

Pages: 1... 567
Can someone PLEASE tell me why does the topic
SGM3 wrote:
I am trying to understand loops
have 6 full pages?!?
Last edited on
@viliml
Because they're trying to learn. I'd prefer one long thread about what they're having issues with instead of 10 new threads a week.

@SGM3
This is the function I am having a problem with

What exactly are you having issues with?
This function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void enterNum (double& entNum1, double& entNum2)
{
    while ((std :: cout << "Enter first number: " << std :: endl)
            && (std :: cin >> entNum1) && (entNum1 == 0))
    {
        std :: cout << "Cannot be calculated." << std :: endl;
        std :: cin.clear();
        std :: cin.ignore(std :: numeric_limits < std :: streamsize > :: max(), '\n');
    }

    while ((std :: cout << "Enter second number: " << std :: endl)
            && (std :: cin >> entNum2) && (entNum2 == 0))
    {
        std :: cout << "Cannot be calculated." << std :: endl;
        std :: cin.clear();
        std :: cin.ignore(std :: numeric_limits < std :: streamsize > :: max(), '\n');
    }
}


The rest of the code is in my previous post. I am trying to set this loop up for input error checking. It works fine when numbers are input. But, when I enter anything but a number, it skips out of the loop and outputs a 0 for the first number input and a computer generated number for the second.

Sorry so brief. Have to go to work. Check back in later.
Last edited on
Hi SGM3,

It's been awhile, but I am back.

In your last post, the two while loops are almost the same - why can't you have a GetNumber function that is called twice?

1
2
3
4
if (operators == '+' || operators == '-' || operators == '*' || operators == '/')
    {
        std :: cout << num1 << " " << operators << " " << num2 << " = " << answer << std :: endl;
    }


The problem with this is that it is hard to extend. If you had 20 operators, then your if statement would have 20 comparisons. Really the if isn't necessary - the cout statement could be in a function called PrintAnswer and that could be called from each of the case statements.

The use of functions for Add Subtract etc aren't needed because the can easily done with a short statement in the switch. If the operator required more than several lines of code, then it would be reasonable to make it a function. An example might be convert radians to degrees, minutes, seconds.

But, when I enter anything but a number, it skips out of the loop and outputs a 0 for the first number input and a computer generated number for the second.


1
2
while ((std :: cout << "Enter second number: " << std :: endl)
            && (std :: cin >> entNum2) && (entNum2 == 0))


So, to understand what is happening with the while condition. You have 3 things separated by && operators. So all of the 3 things have to evaluate to true for the code in braces to execute. The first is easy, a cout which will nearly always be true. The second a cin, will be false if the user doesn't enter a number - this is the problem - the code in braces isn't executed. The third has the same effect if zero is entered, but only if entNum2 is an integer type. && (entNum2 == 0.0) won't work either because you can't compare floats / doubles that way. So if any of the 3 things fail, the error reporting doesn't happen.
a computer generated number for the second.
Probably means entNum2 wasn't initialised.

Now I have just seen this, which you posted much earlier. It is quite different.

1
2
while ((std :: cout << "Enter first number: " << std :: endl)
            && (std :: cin >> entNum1) || (entNum1 < 1))


The difference is the || operator, but the logic seems backwards to me - the body of the loop should only execute if there is a problem, right? You could negate the cin with the ! operator like this:

1
2
while ((std :: cout << "Enter first number: " << std :: endl)
            && !(std :: cin >> entNum1) || (entNum1 < 1))


Anyway, I wouldn't recommend using it for doubles because of the zero comparison.

Also, be careful using && and || without using parentheses to force the intended precedence. In this example the cout and cin are bound together because && has higher precedence than ||.

Just wondering where you found this code? Could be interesting to read all of what they said.

Here's a couple things you could have a go at:

Write the calculator program using a single class. The design is still the same:


Get a number
get an operator
get a number
calc answer


Your IDE should create .h file and a .cpp file when you create the class. Put all the declaration in the .h file, and the definitions of functions in the .cpp file. Create the object in the main.cpp file. You should have minimal code in main().
Think about which functions will be private and which are public. See how you go, once it works for basic functions, you could extend it to cope with lots of extra functions.


The other little project could be to implement K&R calculator that uses a stack.

I found this, The C programming book by Kernighan & Ritchie Second edition. Well worth reading - takes you through all the basics very well.

http://zanasi.chem.unisa.it/download/C.pdf


Chapter 4 has the calculator - there is a website that has all the code in one place, I had trouble finding it.

The K&R Reverse Polish Notation (RPN) calculator works like this:


//Get some input
//if it's a number push it onto stack
// if it's an operator, pop stack & calc answer


Have a go at implementing this using a class and a <stack> STL container.



I just wanted to touch base with you before I start implementing these new ideas.

I found the while loop line of code on this site:


I am struggling with the classes. I have been able to find a nice presentation of basic c++ for gaming purposes where they go over classes, here:

The first DVD is available for free. There is visual and verbal teaching which is nice, but I am still struggling. I bought a few more books with the thought in mind that different text or explanations will make a light bulb go off. Plus I don't see a downside to owning more technical books.

I got the code to work using '!' to negate the cin before your response. I even did a little research to create a custom icon for the compiled program. (A lot easier than I thought it would be) I used a line of code you probably don't approve of as many forums indicated issues with using it.
system("CLS");
But I didn't see the harm in using it for my purposes as long as I don't make it a habit, and I won't.

Anyways glad you are back. Felt a little lost without your guidance haha I will open the source and take a different approach as you mentioned.
OK, the while loop you found had the ! in it, so be careful copying code & changing it - that one character reverses the logic.

Classes can be tricky to understand (because they can introduce a lot of new topics), but if there is only one, it's almost the same. The only real difference is that the code is encapsulated (grouped, say) into the class. The design is still the same, the functions are still the same. The extra thing to think about is which variable and functions are to be private, and which will be public. The rule is to make everything private, then expose the necessary variables (if any) with public get and / or set functions. Of course you would have public functions to allow necessary interaction with the object. The other thing is constructors, but you can get away with having a default constructor, and in this case not have one at all. Your IDE should make a default constructor and destructor automatically.

An example might be a Rectangle class. It would have private width and height variables, public CalcArea and CalcPerimeter functions, that do calculations using width & height.You would also have public getWidth and getHeight functions that return the private values. In this state the rectangle objects would be conceptually constant because there is no way to change width or height. This might be exactly what you want - the width & height might have come from a file so you don't want to be able change any of them.

The next issue is whether Area & Perimeter could be variables, because if the object is to be heavily used, then you might not want to calc these things every time. In this scenario Area & Perimeter would be private variables with public getArea and getPerimeter functions to access that information. Then we could have public setWidth and setHeight functions that change the private Width and Height and recalculate Area and Perimeter using the now private CalcArea and CalcPerimeter functions.

This rectangle class is a good one, maybe you would like to have ago at that (Create a rectangle class as I have explained it), I can think of all kinds of ways this can be extended. If you have any questions, start a new thread.

About other ways of learning, there are beginner exercises on this site. You can get help because there are lots of people who have already done them. There is also Euler and online judge websites that have lots of interesting problems - I have been doing 1 or 2 of these myself (on top of my usual project).

With the system("CLS"); there is an article on this site, all about that topic.

Finally, about the Linux OS - I am not suggesting that you get rid of the Windows system entirely - have both. You will probably need another hard drive, unless you have a spare partition which is probably unlikely. I still have windows because I have an expensive CAD system which I use for work sometimes.
Topic archived. No new replies allowed.
Pages: 1... 567