C++ Basics Cheat Sheet
Types, operators, input and output, strings, conditions, loops, and functions at a glance.
Updated
Program structure#
#include <iostream> // std::cout, std::cin
#include <string> // std::string
int main() {
std::cout << "Hello, C++!\n";
return 0; // optional in main
}g++ -std=c++20 -Wall -Wextra main.cpp -o app
./appTypes and variables#
int count = 42; // whole number (usually 32-bit)
long long big = 9'000'000'000LL;
double price = 49.99; // decimal (prefer over float)
char grade = 'A'; // one character, single quotes
bool ok = true; // true / false
std::string name = "Asha"; // text, double quotes
auto total = price * count; // type deduced: double
const double tax = 0.18; // cannot change
constexpr int days = 7; // compile-time constantOperators#
7 / 2; // 3 (int / int)
7.0 / 2; // 3.5
7 % 2; // 1
static_cast<double>(7) / 2; // 3.5
std::pow(2, 10); // 1024 (from <cmath>, returns double)Conversions#
int n = std::stoi("42"); // string -> int
double d = std::stod("3.75"); // string -> double
std::string s = std::to_string(99); // number -> string
int rounded = static_cast<int>(std::round(4.6)); // 5
int digit = '7' - '0'; // 7Input and output#
int age = 0;
std::cin >> age; // read a number (one word)
std::string line;
std::getline(std::cin >> std::ws, line); // read a whole line after >>
std::cout << "Age: " << age << '\n'; // '\n' rather than std::endl
std::cout << std::fixed << std::setprecision(2) << 3.14159; // 3.14 (<iomanip>)
std::cout << std::boolalpha << true; // true instead of 1Strings#
std::string s = "Hello";
s.size(); // 5
s[0]; // 'H'
s += ", C++"; // "Hello, C++"
s.substr(0, 5); // "Hello"
s.find("C++"); // 7, or std::string::npos if missing
s.replace(0, 5, "Hi"); // "Hi, C++"
s.empty(); // false
s.starts_with("Hi"); // true (C++20)Conditions#
if (score >= 90) {
grade = 'A';
} else if (score >= 75) {
grade = 'B';
} else {
grade = 'C';
}
switch (day) { // integers, chars, enums only
case 6:
case 7:
std::cout << "weekend\n";
break; // don't forget break
default:
std::cout << "weekday\n";
}Loops#
for (int i = 0; i < 5; ++i) { } // 0, 1, 2, 3, 4
for (const auto& item : items) { } // each element, no copies
for (auto& item : items) { item *= 2; } // modify in place
while (balance < target) { } // check first
do { } while (choice != 0); // runs at least once
break; // leave the loop
continue; // skip to the next iterationFunctions#
int square(int n) { // by value: a copy
return n * n;
}
void add_bonus(double& salary) { // by reference: can change it
salary += 5000;
}
double average(const std::vector<int>& v); // read big objects without copying
void greet(const std::string& name, int times = 1); // default argument
int area(int side); // overloads: same name,
int area(int width, int height); // different parametersCommon compiler errors#
Want the full explanations? Go to the Learn C++ course →