Reputation: 23
If the sales manager does not enter any sales amounts, the program should display the “Invalid Input” message.
double sales = 0.0;
double totSales = 0.0;
double aveSales = 0.0;
int ctr = 0;
cout << "Please enter sales amount: \n";
for (int x = 0; x >= 0; x++){
cout << ">>";
cin >> sales;
if (sales > 0){
totSales += sales;
cout << endl;
}
else if (sales == 0){
cout << "Invalid input.\n\n";
x = x - 1;
}
else{
ctr = x;
x = -2;
}
}
aveSales = totSales / ctr;
cout << "Average Sales: " << aveSales << endl;
I already tried length, size, empty, fail and null. None of them work.
else if (sales == 0 || this where I added the second condition for empty input){
cout << "Invalid input.\n\n";
x = x - 1;
}
Upvotes: 0
Views: 911
Reputation: 2567
cin >> sales
returns std::istream
object.
In C++11 and later standards , std::istream
object will be converted to bool
, only if we use it in if
or while
.
You can use : if(cin >> sales)
to check for valid input.
References :
Upvotes: 1
Reputation: 528
I would propose getting the standard input as a std::string
and check it for emptiness:
std::string sales;
// ...
getline(std::cin, sales);
if (sales.empty() || 0 == std::stod(sales)) {
std::cout << "Invalid input!\n";
}
else {
double salesVal = std::stod(sales);
// and so forth
}
This will also make sure the entered value is a valid double value.
Upvotes: 0