Why is it that when I type in -5 for example follow by 5 it still shows period can't be negative?

Viewed 54

Here is my code, is it because of the placement of the function in the while loop? This code is a shorten version. As the title has mentioned already, whenever I tested with only doubles it works, but when I type in a negative value follow up with a normal double it will show the error message "Period cant be negative, please reenter".

This is the code:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double check( double x )
{
   bool ok;
   do
        {
          ok=true;
          if (!cin)                           
          {
               ok = false;
               cin.clear();                       
               cin.ignore(1000,'\n');          
          }
          else    
          {
               string test;
               getline(cin, test);            
               if (test.find_first_not_of( " " )!= string::npos) 
               ok = false;
          }
          if (!ok) 
          {
               cout << "Invalid period,please try again: ";
               cin>>x;
          }
        }while(!ok);
}

int main()
{
    char choice;
    double length[12]={2.50,2.75,3.00,3.25,3.50,3.75,4.00,4.25,4.50,4.75,5.00,5.25};
    double period[12],x;
    bool firstloop=true,ok;
    cout<<"Enter the period measured for the following pendulum lengths: "<<endl;
    for(int i=0;i<12;i++)
    {
        cout<<fixed<<setprecision(2)<<length[i] <<" m  : ";
        cin>>period[i];
        check(period[i]);
        while(period[i]<=0)
        {
            cout<<"Period cant be negative, please retype the period "<<endl;
            cout<< length[i]<<" m  : ";
            cin>>period[i];
            check(period[i]);
        }
        if(firstloop==false)
        {
            while(period[i]<=period[i-1])
            {
                cout<<"Period cant be lower or the same as previous value, please retype (Previous period value: "<< period[i-1]<<")"<<endl;
                cout<< length[i]<<" m  : ";
                cin>>period[i];
                check(period[i]);
            }
        }
        firstloop=false;
    }
}
0 Answers
Related