#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::fixed;
#include <iomanip>
#include "salesp.h"
// initialize elements of array sales to 0.0
SalesPerson::SalesPerson()
{
for ( int i = 0; i < 12; i++ )
sales[ i ] = 0.0;
} // end SalesPerson constructor
// get 12 sales figures from the user at the keyboard
void SalesPerson::getSalesFromUser()
{
double salesFigure;
for ( int i = 1; i <= 12; i++ ) {
cout << "Enter sales amount for month " << i << ": ";
cin >> salesFigure;
setSales( i, salesFigure );
} // end for
} // end function getSalesFromUser
// set one of the 12 monthly sales figures; function subtracts
// one from month value for proper subscript in sales array
int SalesPerson::setSales( int month, double amount )
{
cout << amount << endl;
// test for valid month and amount values
if ( month >= 1 && month <= 12 && amount > 0 )
sales[ month - 1 ] = amount; // adjust for subscripts 0-11
else // invalid month or amount value
cout << "Invalid month or sales figure" << endl;
} // end function setSales
The header file:
1 2 3 4 5 6 7 8 9 10 11
class SalesPerson {
public:
SalesPerson(); // constructor
void getSalesFromUser(); // input sales from keyboard
int setSales( int, double ); // set sales for a month
private:
double sales[ 12 ]; // 12 monthly sales figures
};
Now if we run:
1 2 3 4 5 6 7 8 9 10 11 12
#include "salesp.h"
usingnamespace std;
int main()
{
SalesPerson s; // create SalesPerson object s
s.getSalesFromUser(); // note simple sequential code; no
return 0;
}
If I enter a character,which is worng, the loop continious without prompting me to enter any number. Why is that?
I can't understand why it continious. I don't check to see what the user enters in the code but when I am trying to sign a char to a double, wouldn't the for "break" or continue prompting me to enter data?
Enter sales amount for month 1: k
Invalid month or sales figure
Enter sales amount for month 2: Invalid month or sales figure
Enter sales amount for month 3: Invalid month or sales figure
Enter sales amount for month 4: Invalid month or sales figure
Enter sales amount for month 5: Invalid month or sales figure
Enter sales amount for month 6: Invalid month or sales figure
Enter sales amount for month 7: Invalid month or sales figure
Enter sales amount for month 8: Invalid month or sales figure
Enter sales amount for month 9: Invalid month or sales figure
Enter sales amount for month 10: Invalid month or sales figure
Enter sales amount for month 11: Invalid month or sales figure
Enter sales amount for month 12: Invalid month or sales figure
Process returned 0 (0x0) execution time : 2.583 s
It is because cin loses its integrity when it handles the wrong input type. Keep searching for better ways to get input from the user. There are many great examples on this Website.