"agent349" <ag******@yahoo.com> wrote in message
news:e2**************************@posting.google.c om...
Hi,
I'm fairly new to c++. I need user input in the form of dollar
amounts, ie: "$10.00". I'd like to remove the dollar sign "$" then
store the rest in a variable. How do I go about removing the dollar
sign? Thanks in advance!
What sort of variable? int, double, some custom money type?
Integer variables are the best for manipulating money, just count you money
in cents, and then convert to dollars when you have to output figures. A
typical newbie error is 'money prints with a period, therefore I must use a
double or a float because they print with periods'. That is an error, money
is an integral quantity, you only ever have a whole number of cents,
therefore integers are the correct thing to use. How you print a money total
has got nothing to do with it.
There are lots of ways to do what you want, here's one way. It works but it
may not do exactly what you want since your requirements are not clearly
defined.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "enter some money (like this $12.34) "
char dummy1, dummy2;
int dollars, cents;
cin >> dummy1 >> dollars >> dummy2 >> cents;
int total_cents = 100*dollars + cents;
cout << "You entered $" << total_cents/100 << '.' << setfill('0') <<
setw(2) << total_cents%100 << '\n';
}
This is untested code.
The dummy1 and dummy2 variables are there just to absorb the dollar sign and
period from the input.
The last line shows how you can pretty print a money value from an int
variable which is a number of cents.
The big problem with this program is that it makes no attempt to deal with
incorrect input on the part of the user, it will accept some incorrect input
and barf on others. But you didn't specify what you wanted to happen on
incorrect input (or even what correct input was) so I ignored that issue.
john