C++ Cheat Sheet

A classic one

#In & Output

Hello World!

#include <iostream>:
using namespace std;

int main(int argc, const char * argv[]) {
    cout << "Hello World!";
}
// with a line break:
cout << "Hello World!\n";
// generates the same result:
cout << "Hello World!" << endl;
Important: you need to include #iostream.

Combining Outputs

cout << "First " << "Second " << "Thrid";
cout << "First" << endl << "Second";
// printing the return-value of a function:
int add(int x) {
    return x+x;
}

int main(int argc, const char * argv[]) {
    cout << add(2); // 4
}

Getting User Input

std::cout << "Enter string:" << endl;
std::string s;
std::getline(std::cin, s);
std::cout << "the string was: " << s << std::endl;

#Functions

Return-Statement

int add(int x) {
    return x;
}
You can only return one value.

Multiple Parameters

int add(int x, int y) {
    return x+y;
}
// this won't work:
int add(int x, y) {
    return x+y;
}
Unlike e.g. in Go, there is no shorthand syntax for multiple parameters with the same data type. We have to cut them out.

Function overloading

int add(int x) {
    cout << "int function";
    return x+x;
}

double add(double x) {
    cout << "double function";
    return x+x;
}

int main(int argc, const char * argv[]) {
    cout << add(2.5); // double function
    cout << add(2);   // int function
}
We can create two or more functions with the same name - as long as they have different datatypes, only the function with the matching datatype will be executed. s