-1

How can I make sure the user enters a positive number, and if its negative give them an error and make them retype it?

int main()
{
    float sq, n;
    cout << "Enter any number:";
    cin >> n;
    sq = sqrt(n);
    cout << "Square root of " << n << " is " << sq;
    return 0;
}
  • A while loop to check it. If negative, loop again – Louis Go Oct 18 '21 at 01:47
  • Are you asking how loops work? What kind of loop to use? Where to put it? What the condition should be? Have you thought about what part of your code should repeat? – Drew Dormann Oct 18 '21 at 01:50
  • Does this answer your question? [How to check if input is numeric in C++](https://stackoverflow.com/questions/5655142/how-to-check-if-input-is-numeric-in-c) – Karl Oct 19 '21 at 07:56

2 Answers2

0

This can be achieved easily with a do-while loop:

int num = 0;
do {
    std::cin >> num;
} while (num < 0)
kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
0

here, you can use while loop and if-else statement within while loop.

int main()
{
    float sq;
    int n;
    
    cout << "Enter any number:\n";
    while (cin >> n) {
    
      if (n < 0)
        cout << "enter a positive number\n";
      
      else {
      sq = sqrt(n);
      cout << "Square root of " << n << " is " << sq << '\n';
      cout << "Enter any number: \n";
      } 
    }
    return 0;
}
Jitu DeRaps
  • 144
  • 1
  • 9