Tuesday, November 6, 2012

C++ literal constant, type and format


Simple note:

Code:

literal_constant_test.cpp

#include <iostream>
#include <iomanip>
using namespace std;

/** test literal constant,
 * also try show their type and format them with cout
 */
int main() {
    cout << "\tvalue - type: " << endl << endl << "\t"
        << 11 << " - " << typeid(11).name() << "(int)" << endl << "\t" // int
        << 011 << " - " << typeid(011).name() << "(int)" << endl << "\t" // int, octonary
        << 0x11 << " - " << typeid(0x11).name() << "(int)" << endl << "\t" // int, hex
        << 11U << " - " << typeid(11U).name() << "(unsigned int)" << endl << "\t" // unsigned int
        << 11L << " - " << typeid(11L).name() << "(long)" << endl << "\t" // long
        << 11UL << " - " << typeid(11UL).name() << "(unsigned long)" << endl << "\t" // unsigned long
        << setprecision(2) << fixed // change to fixed format, 11.0 -> 11.00
        << 11.0 << " - " << typeid(11.0).name() << "(double)" << endl << "\t" // double
        << noshowpoint << setprecision( 0 )  // change to no point, 11.0 -> 11
        << 1.1e1 << " - " << typeid(1.1e1).name() << "(double)" << endl << "\t" // double
        << scientific // change to scientific notation, 11.0 -> 1.10e+001
        << 11.0F << " - " << typeid(11.0F).name() << "(float)" << endl << endl; // float
    system("PAUSE");
    return 0;
}


Result:



References:

http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout

http://stackoverflow.com/questions/81870/print-variable-type-in-c

http://www.cplusplus.com/reference/iostream/manipulators/fixed/

http://www.cplusplus.com/reference/iostream/manipulators/noshowpoint/

File at github:

https://github.com/benbai123/C_Cplusplus_Practice/blob/master/CPP/CPP_Basic/literal_constant_test.cpp

No comments:

Post a Comment