How to allow input of numbers greater than or equal to zero, but exclude everything else?

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!
Last edited on
Normally you read the input into a string and convert it to a number and check if you number is ok.
A little demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int getIntGreaterThanZero()
{
  std::string input;
  int num = 0;

  for(;;)
  {
    std::cout << "Enter a number greater than zero: ";
    std::cin >> input;
    try
    {
      num = std::stoi(input);
      if (num > 0)
        return num;

      std::cerr << "\a\nInvalid input\n";
    }
    catch(const std::invalid_argument& ex)
    {
      std::cerr << "\a\nInvalid input\n";
    }
  }
}

Same principle applies for other values or doubles
too bothersome.

if you really want, you may simply check the stream.
if( std::cin ) //reading was successful
If I may embellish Thomas1965's solution...
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>

int getIntGreaterThanZero();

int main()
{
    std::cout << "Please insert shape type: ";
    std::string shape;
    std::getline(std::cin, shape); // read a line; discard terminating '\n'

    if (shape == "a") {
        std::cout << "Please insert side length: ";
        double square = getIntGreaterThanZero(); // implicitly converted to double

        double s_circ = (square*square);
        double s_area = (4*square);

        std::cout << "The circumference is: " << s_circ
        << "\nThe area is: " << s_area << '\n';
    }
    return 0;   
}

int getIntGreaterThanZero()
{
    std::string input;
    int num = 0;

    while(!num)
    {
        std::cout << "Enter a number greater than zero: ";
        std::cin >> input;
        std::cin.ignore(1000, '\n');
        try
        {
            num = std::stoi(input);
            if (num > 0)
                return num;
            std::cerr << "\a\nInvalid input\n";
            num = 0; // prevent exiting from while-loop
        }
        // std::stoi may throw both std::invalid_argument and std::out_of_range
        catch(const std::invalid_argument& ex)
        {
            std::cerr << "\a\nInvalid input\n";
            num = 0; // prevent exiting from while-loop
        }
    }
}


Last edited on
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
26
#include <iostream>

int get_int( int minv, int maxv )
{
    std::cout << "enter an integer in [" << minv << ',' << maxv << "]: " ;

    int number ;
    if( std::cin >> number )
    {
        if( number >= minv && number <= maxv ) return number ;
        else std::cout << "error: value " << number << " is out of range." ;
    }
    else std::cout << "error: non integer input." ;

    std::cin.clear() ; // clear a possible failed state
    std::cin.ignore( 1000, '\n' ) ; // discard this line of input
    std::cout << " try again\n" ;
    return get_int( minv, maxv ) ; // try again
}

int main()
{
    std::cout << "radius? " ;
    const int radius = get_int( 1, 1000000 ) ;
    std::cout << "you entered " << radius << '\n' ;
}
Topic archived. No new replies allowed.