taking decimal input from the user in c++
I want the input for the price in decimal format(15.00). If the input is in integer format then I want to convert it to decimal format.
The maximum price for a sale is 999.99 and minimum is 0.00.
I have tried so far:
Code:
#include<iostream>
using std::cout;
using std::cin;
void main(){
float eventPrice;
bool cPrice = true;
while (cPrice)
{
cout << "Please enter the event ticket price:";
cin >> eventPrice;
if (eventPrice <= 999.99 && eventPrice>=0) cPrice = false;
else
{
cout << "Invlaid price. Try again!!";
}
}
cout << "the price is:";
cout << eventPrice;
}
Avalid input will be:
1.8,
0.8,
0.00,
0,
9,
99
Re: taking decimal input from the user in c++
so what problem exactly do you have with the posted code snippet?
Re: taking decimal input from the user in c++
The input routine will do as you want. If you require the output to be displayed in a certain way then there are io manipulators that can be used for this. See http://www.cplusplus.com/reference/iomanip/
eg setw() will set the field width for the output and setprecision() will set the decimal precision to be used. Also fixed which will provide a fixed number of decimal digits. See http://www.cplusplus.com/reference/ios/fixed/?kw=fixed
Note that you will need to include <iomanip>
PS Your routine will allow an input of say 23.4567 (which can be displayed as 23.46) . If you only want to allow an input of no more than 2 dp then that is a different issue.