Writing and Reading Currency - C++ Internationalization

C++ examples for Internationalization:Locale

Description

Writing and Reading Currency

Demo Code

#include <iostream>
#include <locale>
#include <string>
#include <sstream>

using namespace std;

long double readMoney(istream& in, bool intl = false) {

   long double val;

   const money_get<char>& moneyReader = use_facet<money_get<char> >(in.getloc());

   istreambuf_iterator<char> end;

   ios_base::iostate state = 0;//w ww .  j  a  v  a2s. co m

   moneyReader.get(in, end, intl, in, state, val);

   if (state != 0 && !(state & ios_base::eofbit))
      throw "Couldn't read money!\n";

   return(val);
}

void writeMoney(ostream& out, long double val, bool intl = false) {
   const money_put<char>& moneyWriter = use_facet<money_put<char> >(out.getloc());

   if (moneyWriter.put(out, intl, out, out.fill(), val).failed())
      throw "Couldn't write money!\n";
}

int main() {
   long double val = 0;
   float exchangeRate = 0.775434f;  // Dollars to Euros
   locale locEn("english");
   locale locFr("french");

   cout << "Dollars: ";
   cin.imbue(locEn);
   val = readMoney(cin, false);

   cout.imbue(locFr);

   cout.setf(ios_base::showbase);
   cout << "Euros: ";

   writeMoney(cout, val * exchangeRate, true);
}

Related Tutorials