Problem with looping

I'm making a program that finds the square root of a number. With intergers, it works fine, but I want the program to show and error if the user tries to enter a character or negative number.

I can make an error show with negative numbers, but anytime I use a char, the program loops infinitely. Does anyone know a workaround?
Is there another way to approach this without the use of strings?
What's wrong with strings?
Strings would be easiest, but there is another way to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int CheckInput( int min )
{
    int menuChoice;           	 // Used to determine correct action.
    bool invalid;             	 // Used to check if input is valid.
    do
    {
        invalid = false;
        if ( !( cin >> menuChoice ) )
        {
            cout << "Invalid character, please try again.\n";
            cin.clear();    // This statement will clear the infinite loop.
            invalid = true;
        }
        else if ( menuChoice < min )
        {
            cout << "Please enter a number larger than " << min << ".\n";
            invalid = true;
        }
        cin.ignore( numeric_limits<streamsize>::max(), '\n' );
        // Clears the buffer for future input.
    }
    while( invalid );
    return menuChoice;
}


This should work, good luck.
Last edited on
Use this code its much easy to understand and implement...


#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <math.h>

int valid(int num1)
{
if (num1 > 0 && num1 < 5000)
return 0;
else
return 1;
}

void main ()
{
int num;
float res;
clrscr();
cout<<"Enter Number : ";
cin>>num;
if (valid(num) == 0)
{
res=sqrt(num);
cout<<res;
}
else
{
cout<<"Invalid number";
}
getch();
}
That isn't standard C++
Topic archived. No new replies allowed.