Hello!
I've recently started learning C++ in a course at university. So far, so good. However, there is one problem I've been trying to solve for hours now and I just don't know any more. Any advice would be appreciated.
We are to make a program that calculates the circumference and area of a 2D object. Naturally, we have to exclude results that are less than zero and disallow input for numbers less than zero as invalid. The input for the equation cannot be anything else than a number.
I've figured most of it out, but I have no clue how to make my program exclude input that isn't a number but at the same time include zero.
One of the pieces I can't get around:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
string shape;
double square, s_circ, s_area;
cin >> shape;
if (shape == "a") {
cout << "The length of the side:" << endl;
cin >> square;
s_circ = (square*square);
s_area = (4*square);
if (square>=0 && s_circ>=0 && s_area>=0) {
cout << "The circumference is: " << s_circ << endl;
cout << "The area is: " << s_area << endl;
}
else { cout << "Invalid input." << endl; }
}
|
(Please, ignore any awkward text, I translated quickly from my native language.)
So, when I set the conditions to >= 0, then my program accepts whatever other characters ("blabla", "+-", etc.) as valid and the result of the equations is 0. When I tried limiting the input to numbers by using isdigit, then the program doesn't recognise 0 as valid input. I tweaked and tweaked, then looked and looked, but I only found solutions for how to limit number input to specific numbers.
Is there some sort of issue with how C++ understands the value of zero? Or have I made a mistake in setting the conditions the way I tried? Is there a way to limit input to numbers greater than and equal to zero exclusively? Without it accepting whatever other characters the user might try to put in for laughs. I know that a square with 0 area and circumference is no square, but it should still be able to tell the user that the result is zero if they choose to work with zero.
Thank you for your time!