Outputting time and money

The put_time function in <iomanip> is passed a tm structure initialized with a time and date and a format string. The function returns an instance of the _Timeobj class. As the name suggests, you are not really expected to create variables of this class; instead, the function should be used to insert a time/date with a specific format into a stream. There is an insertion operator that will print a _Timeobj object. The function is used like this:

    time_t t = time(nullptr); 
tm *pt = localtime(&t);
cout << put_time(pt, "time = %X date = %x") << "n";

The output from this is:

    time = 20:08:04 date = 01/02/17

The function will use the locale in the stream, so if you imbue a locale into the stream and then call put_time, the time/date will be formatted using the format string and the time/date localization rules for the locale. The format string uses format tokens for strftime:

    time_t t = time(nullptr); 
tm *pt = localtime(&t);
cout << put_time(pt, "month = %B day = %A") << "n";
cout.imbue(locale("french"));
cout << put_time(pt, "month = %B day = %A") << "n";

The output of the preceding code is:

    month = March day = Thursday
month = mars day = jeudi

Similarly, the put_money function returns a _Monobj object. Again, this is simply a container for the parameters that you pass to this function and you are not expected to use instances of this class. Instead, you are expected to insert this function into an output stream. The actual work occurs in the insertion operator that obtains the money facet on the current locale, which uses this to format the number to the appropriate number of decimal places and determine the decimal point character; if a thousands separator is used, what character to use, before it is inserted it in the appropriate place.

    Cout << showbase; 
cout.imbue(locale("German"));
cout << "German" << "n";
cout << put_money(109900, false) << "n";
cout << put_money("1099", true) << "n";
cout.imbue(locale("American"));
cout << "American" << "n";
cout << put_money(109900, false) << "n";
cout << put_money("1099", true) << "n";

The output of the preceding code is:

    German
1.099,00 euros
EUR10,99
American
$1,099.00
USD10.99

You provide the number in either a double or a string as Euro cents or cents and the put_money function formats the number in Euros or dollars using the appropriate decimal point (, for German, . for American) and the appropriate thousands separator (. for German, , for American). Inserting the showbase manipulator into the output stream means that the put_money function will show the currency symbol, otherwise just the formatted number will be shown. The second parameter to the put_money function specifies whether the currency character (false) or the international symbol (true) is used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset