-2

Program to take negative input This program works perfectly with int but when inputting float it become infinite loop. why ?

#include<iostream>
using namespace std;
int main(){

     int positive = 0;
     
     while(positive>=0){
          cout<<"Enter number"; cin>> positive;
          if (positive<0){
               cout<<"yes it is negative";
          }
     }
     
     return 0;
}
  • 1
    What number did you enter? Have you considered adding error checking to the input? Once the stream goes bad because `.` is not an int it won't read again unless you clear the error and ignore the invalid input. – Retired Ninja Sep 25 '22 at 05:36

1 Answers1

2

Why? Because C++ is a typed language and it can't accept a float value into int variable without conversion.

How to fix it?

    cin >> positive;

    if (cin.fail()) {
        cin.clear();
        cin.ignore(256, '\n');
    }

One way is to add an error check. But I'd argue a better way is to just use float variable (error checking is still useful) TL;DR Change int positive to float

Morbius
  • 21
  • 4