-
strange problem
I am getting problem with this code(compiled with dev c++)
Code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i;
double x;
cout << "\n Enter the double value";
cin>>x;
cout<<"\n Enter a positive integer ";
cin>>i;
while(i<1){
cerr<<"error i= "<<i<<endl;
cout<<"enter a positive integer: ";
cin>>i;
};
cout<<"i*x= "<<i*x<<endl;
getch();
return 0;
}
When i enter the any value for i greater than 1 it is working fine.
But when i enter the floating point value less than 1 it goes into infinite loop.
PHP Code:
Example input which leads to infinite loop
enter a double value :46.7
Enter a positive integer: 0.56
i am experimented with other float values -4.56,-3.5 any float less than 1.
my doubt is that, i is integer, so it should takes only value without fraction part. It is works fine for i=0 and why not for 0.67 or any floating less than 1.
-
It's probably because you left the unused decimal part of the int in the buffer and cin is continuously trying to read that stuff into i. So, clean the buffer.
#include <limits>
cin.ignore(numeric_limits<streamsize>::max(), '\n');
This was a FAQ question, I just had to find it. Learn to FAQ before posting.
-
Thanks
Thank you very much
Now its working fine.
As you suggested i will read the FAQ before posting.