Cpp - Read hexadecimal digits and a floating-point number

Integers

You can use the hex, oct, and dec manipulators to stipulate that any character sequence input is to processed as a hexadecimal, octal, or decimal number.

int n; 
cin >> oct >> n; 

An input value of 10 will be interpreted as an octal, which corresponds to a decimal value of 8.

cin >> hex >> n; 

Here, any input will be interpreted as a hexadecimal, enabling input such as f0a or -F7.

Floating-Point Numbers

The >> operator interprets any input as a decimal floating-point number if the variable is a floating-point type, i.e. float, double, or long double.

The floating-point number can be entered in fixed point or exponential notation.

double x; 
cin >> x; 

The character input is converted to a double value in this case. Input, such as 123, -22.0, or 3e10 is valid.

Demo

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

int main() // w w  w  . ja va  2 s.  c o  m
{ 
    int number = 0; 

    cout << "\nEnter a hexadecimal number: " << endl; 
    cin >> hex >> number;      // Input hex-number 

    cout << "Your decimal input: " << number << endl; 

    // If an invalid input occurred: 
    cin.sync();              // Clears the buffer 
    cin.clear();             // Reset error flags 

    double x1 = 0.0, x2 = 0.0; 

    cout << "\nNow enter two floating-point values: " << endl; 

    cout << "1. number: "; 
    cin  >> x1;                     // Read first number 
    cout << "2. number: "; 
    cin  >> x2;                     // Read second number 

    cout << fixed << setprecision(2) 
         << "\nThe sum of both numbers:   " 
         << setw(10) << x1 + x2 << endl; 

    cout << "\nThe product of both numbers: " 
         << setw(10) << x1 * x2 << endl; 

    return 0; 
}

Result

Exercise