The code follows after this intro.
Look how I also added code to intercept bad input like characters and floating point numbers. So input like
j and
2.51 are intercepted. Try it. However, CTRL-Z/D is accepted. /D for *nix systems (bash instead of console).
Also,
2.0 is accepted as well. Since the value is exactly an integer. See if you like it:
Code:
#include <iostream>
#include <string>
#include <limits> //numeric_limits #include <iomanip> //setprecision etc. #include <cmath> //modf() using namespace std;
//Optional function. Depends on IDE. Remove for release version. void wait_for_enter();
int main()
{
int num_positives(0), num_negatives(0), num_evens(0), num_odds(0);
double percent_negatives(0), percent_positives(0), percent_evens(0),
percent_odds(0);
//Lets make this double, so no cast is needed later in the %-calculations. double total_inputs(0);
double input; //Trick to check for fractions, wich is also invalid input. int theNumber; ///For conversion from double to int. while(1)
{
//need this bogus variable for modf(). modf() requires it. double intpart;
cout<<"Please enter an integer (pos or neg). CTRL-Z/D to quit!\n";
while(!(cin>>input) || modf(input , &intpart) !=0 )
{
//CTRL-Z/D entered? If so, then get out of this loop. if(cin.eof())
break;
cout<<"You didn't enter a number. Try again please."<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
//CTRL-Z/D entered? If so, then get out of this loop as well. if(cin.eof() )
break;
total_inputs++;
//Lets convert, since we need modulo calculation (can't with type double).
theNumber = static_cast<int> (input);
if(theNumber%2 == 0)
num_evens++;
else
num_odds++;
if(theNumber<0)
num_negatives++;
else
num_positives++;
}
/*CTRL-Z/D is entered, so we end up here. */
cout<<"\t\tTHE RESULTS OF THE ENTRIES"<<endl;
cout<<"\t\tTotal valid integers: "<<total_inputs<<endl;
cout<<"\t\tTotal positive numbers: "<<num_positives<<endl;
cout<<"\t\tTotal negative numbers: "<<num_negatives<<endl;
cout<<"\t\tTotal even numbers: "<<num_evens<<endl;
cout<<"\t\tTotal odd numbers: "<<num_odds<<endl;
//Skip if no valid input: avoid dividing by zero and unneeded calculations. if(total_inputs > 0)
{
//Lets show 10 digit-precision.
cout<<fixed<<setprecision(10);
cout<<"\t\tPercent positive numbers: "<<
num_positives/total_inputs*100<<"%"<<endl;
cout<<"\t\tPercent negative numbers: "<<
num_negatives/total_inputs*100<<"%"<<endl;
cout<<"\t\tPercent even numbers: "<<
num_evens/total_inputs*100<<"%"<<endl;
cout<<"\t\tPercent odd numbers: "<<
num_odds/total_inputs*100<<"%"<<endl;
}
else
cout<<endl<<"\t*** STATISTICS OMITTED: no (valid) integers entered ***"<<endl;
//Optional. Depends on IDE. Remove for release version.
wait_for_enter();
return 0;
}
//Optional. Depends on IDE. Remove for release version. void wait_for_enter()
{
cout << "press <enter> to continue...\n";
// Reset failstate, just in case.
cin.clear();
string line;
getline( cin, line);
}