strange problem

This is a discussion on strange problem within the C++ Programming forums, part of the General Programming Boards category; I am getting problem with this code(compiled with dev c++) Code: #include <iostream> #include <conio.h> using namespace std; int main() ...

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    2

    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.

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,714
    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.
    Last edited by whiteflags; 06-19-2006 at 01:58 AM. Reason: faq link

  3. #3
    Registered User
    Join Date
    Jun 2006
    Posts
    2

    Thanks

    Thank you very much
    Now its working fine.
    As you suggested i will read the FAQ before posting.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange problem with GETLINE
    By wco5002 in forum C++ Programming
    Replies: 13
    Last Post: 07-07-2008, 09:57 AM
  2. Strange problem
    By G4B3 in forum C Programming
    Replies: 6
    Last Post: 05-14-2008, 02:07 PM
  3. Strange problem with classes in header files
    By samGwilliam in forum C++ Programming
    Replies: 2
    Last Post: 02-29-2008, 03:55 AM
  4. Strange problem
    By ~Kyo~ in forum Game Programming
    Replies: 0
    Last Post: 02-14-2006, 09:35 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21