1. Interactive Streams: std::cin and std::getline
While std::cout writes outward to the console display, `std::cin` (Character Input) reads incoming characters from the keyboard buffer:
[ Keyboard Typing: "42" + Enter ]
|
v
[ Operating System Stdin Buffer: "42\n" ]
|
v
[ std::cin >> targetVariable ]
- Strips leading whitespace
- Parses ASCII digits "42" into binary 32-bit integer
- Stores binary 42 inside memory allocated for targetVariableThe Pitfall of std::cin >> with Strings
The extraction operator (>>) stops reading as soon as it encounters any whitespace (space, tab, or newline). If a user types "Ada Lovelace", std::cin >> name only captures "Ada".
To capture full names or complete sentences, use `std::getline()`:
#include <iostream>
#include <string>
int main() {
std::string fullName;
int userAge;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName); // Reads entire line including spaces
std::cout << "Enter your age: ";
std::cin >> userAge;
std::cout << "Welcome, " << fullName << "! Next year you will be " << (userAge + 1) << "." << std::endl;
return 0;
}2. C++ Arithmetic Operators & The Integer Division Trap
| Operator | Syntax | Description | Example |
|---|---|---|---|
| Addition | + | Sums two operands | 5 + 3 == 8 |
| Subtraction | - | Subtracts right operand from left | 10 - 4 == 6 |
| Multiplication | * | Multiplies two operands | 6 * 7 == 42 |
| Division | / | Divides left operand by right | 7 / 2 == 3 (Integer truncation!) |
| Modulus | % | Computes remainder of integer division | 7 % 2 == 1 |
Crucial Concept: Integer Division vs Floating-Point Division In C++, when both operands of a division are integers, the result is strictly an integer: any fractional decimal part is discarded.
>
> int a = 7;
> int b = 2;
> double badResult = a / b; // Evaluates to 3.0 (7/2 evaluated as integer 3 first!)
> double goodResult = (double)a / b; // Evaluates to 3.5 (explicit cast converts a to double)3. Scientific Math with <cmath>
For advanced calculations like square roots, powers, and trigonometry, include the standard C++ math library:
#include <iostream>
#include <cmath>
#include <iomanip>
int main() {
double base = 5.0;
double exponent = 3.0;
std::cout << "5 raised to power 3 : " << std::pow(base, exponent) << std::endl;
std::cout << "Square root of 144 : " << std::sqrt(144.0) << std::endl;
std::cout << "Ceiling of 4.12 : " << std::ceil(4.12) << std::endl;
std::cout << "Floor of 4.89 : " << std::floor(4.89) << std::endl;
std::cout << "Absolute value of -9: " << std::abs(-9) << std::endl;
return 0;
}