Printing Numbers in C++
Outputting Numeric Values
The `std::cout` object handles all numeric types in C++ including integers and floating-point numbers, and supports scientific notation.
Key advantages:
- Automatic type conversion to readable format
- No manual memory management needed
- Supports all arithmetic types (`int`, `long long`, `float`, `double`, etc.)
Basic Number Output
Printing different numeric types:
#include <iostream>
int main() {
std::cout << "Integer: " << 42 << '\n';
std::cout << "Float: " << 3.14159f << '\n';
std::cout << "Scientific: " << 6.022e23 << '\n';
return 0;
}
Integer: 42 Float: 3.14159 Scientific: 6.022e+23
Mathematical Expressions
`std::cout` prints the result of expressions (evaluated with normal operator precedence):
#include <iostream>
int main() {
std::cout << "Arithmetic: " << (10 + 5 * 3) << '\n'; // 25
std::cout << "Modulus: " << (17 % 5) << '\n'; // 2
std::cout << "Division: " << (10 / 3) << '\n'; // 3 (integer division)
std::cout << "Float Div: " << (10.0 / 3) << '\n'; // 3.33333 (default precision)
return 0;
}
Arithmetic: 25 Modulus: 2 Division: 3 Float Div: 3.33333
Advanced Formatting
Use `
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589793;
std::cout << "Default: " << pi << '\n';
std::cout << "Fixed 2: " << std::fixed << std::setprecision(2) << pi << '\n'; // 2 digits after decimal
std::cout << "Scientific: " << std::scientific << std::setprecision(6) << pi << '\n'; // 6 digits after decimal in scientific
// Integer base formatting
std::cout << "Hex: " << std::hex << 255 << '\n';
// Reset common flags (optional)
std::cout << std::defaultfloat << std::dec;
}
Default: 3.14159 Fixed 2: 3.14 Scientific: 3.141593e+00 Hex: ff
Integer Bases & Flags
Control integer base and presentation with stream flags:
#include <iostream>
#include <iomanip>
int main() {
int n = 255;
std::cout << "dec: " << std::dec << n << '\n'
<< "hex: " << std::hex << n << '\n'
<< "oct: " << std::oct << n << '\n';
std::cout << std::showbase << std::uppercase;
std::cout << "hex (showbase, upper): " << std::hex << n << '\n'; // 0XFF
std::cout << std::noshowbase << std::nouppercase << std::dec; // reset
}
dec: 255 hex: ff oct: 377 hex (showbase, upper): 0XFF
Best Practices
For production code:
- Initialize variables before output
- Prefer `'\n'` for newlines; reserve `std::endl` (newline + flush) for when output must be immediately visible
- Use constants for magic numbers
- Consider locale-specific formatting where appropriate
- For financial values, prefer fixed notation (`std::fixed` with `std::setprecision(2)`) and consider storing values in integer minor units (e.g., cents) to avoid floating-point rounding issues
- For clearer booleans, use `std::boolalpha` (`true/false` instead of `1/0`)
- Avoid `using namespace std;` in global scope; qualify with `std::`