|
-
February 21st, 2015, 04:08 PM
#1
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
-
February 22nd, 2015, 03:51 AM
#2
Re: taking decimal input from the user in c++
so what problem exactly do you have with the posted code snippet?
Victor Nijegorodov
-
February 22nd, 2015, 06:14 AM
#3
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.
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|