Sam
Sam

Reputation: 23

Read in Dollar Amount (with dollar sign) C++

I need to read in a value (cin) including a dollar sign and a dollar amount, but I only want to read in the amount.

In other words, I have this input: "$3458.5," but I want to read in and store "3458.5"

The current approach I thought of was reading the value in as a string, removing the first character, and then converting to a double. But, I feel like this method is inefficient and there's a better method out there. Any tips? Thanks!

Upvotes: 1

Views: 4148

Answers (4)

pirt
pirt

Reputation: 1213

If you use scanf instead of cin, you can drop the $ if you know it will always be there and write the information directly to a float.

float d;
scanf("$%f", d);

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490098

C++98/03 had a money_get facet to do things like this. Unfortunately, using it was fairly painful (to put it nicely).

C++11 added a get_money manipulator to make life quite a bit simpler. It works something like this:

#include <iostream>
#include <iomanip>

int main() {
    long double amt;

    std::cin.imbue(std::locale(""));
    std::cout.imbue(std::locale(""));

    std::cin >> std::get_money(amt);
    std::cout << std::showbase << std::put_money(amt) << "\n";
}

Now, there are a couple of things to be aware of here. First and foremost, the conversion from the external to internal representation isn't specified, but in the implementations I've seen, $3458.5 will not be read as 3458.5--it'd be read and stored as 345850 -- that is, a count of the number of pennies.

When you use put_money to write the data back out, however, it'll be converted symmetrically with whatever was done during input, so if you entered $3458.5, it'll be written back out the same way.

There is one other caveat: I've seen at least one implementation that was strangely finicky about input format, so it required either 0 or 2 digits after the decimal point during input, so either $3458.50 or $3458 would read fine, but $3458.5 wouldn't be read at all (it'd be treated as a failed conversion).

Upvotes: 1

bipll
bipll

Reputation: 11940

if(stream.peek() == '$') stream.get();
stream >> amount;

Upvotes: 2

Pete Becker
Pete Becker

Reputation: 76245

I agree with Magnus: this seems minor. But if you really want to do it, just read a character then read a double:

char ch;
double d;
std::cin >> ch >> d;

Upvotes: 4

Related Questions