First Delete all // userinput--
values to get an effective prompt in terminal.
Make sure you have g++ installed, name the file main.cpp
and run this
g++ main.cpp -o main.out && ./main.out
#include <fstream> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
void learnTypesAndSize() { | |
/** TYPES */ | |
cout << "\n:::: TYPES ::::" << endl; | |
const double PI = 3.1415926535; | |
char myGrade = 'A'; | |
bool isHappy = true; | |
int myAge = 30; | |
float favNum = 3.141592; | |
// Other types | |
// short int: at least 16 bits | |
// long int: at least 32 bits | |
// long long int: at least 64 bits | |
// unsigned int: same as signed version | |
// long double: not less than double | |
cout << "Fav number: " << favNum << endl; | |
/** SIZE (number of bytes) */ | |
cout << "\n:::: SIZE ::::" << endl; | |
cout << "Size of double: " << sizeof(PI) << endl; | |
cout << "Size of char: " << sizeof(myGrade) << endl; | |
cout << "Size of bool: " << sizeof(isHappy) << endl; | |
cout << "Size of int: " << sizeof(myAge) << endl; | |
cout << "Size of float: " << sizeof(favNum) << endl; | |
int largestInt = 2147483647; // cannot be higher | |
cout << "Largest integer: " << largestInt << endl; | |
largestInt = 2147483648; // goes out of range | |
} | |
void learnMath() { | |
/** ARITHMETIC +, -, *, /, %, ++, -- */ | |
cout << "\n:::: ARITHMETIC ::::" << endl; | |
cout << "5 + 2 = " << 5 + 2 << endl; | |
cout << "5 - 2 = " << 5 - 2 << endl; | |
cout << "5 * 2 = " << 5 * 2 << endl; | |
cout << "5 / 2 = " << 5 / 2 << endl; | |
cout << "5 % 2 = " << 5 % 2 << endl; | |
int five = 5; | |
cout << "5++ = " << five++ << endl; // increment after getting value of five | |
cout << "++5 = " << ++five << endl; // increment before getting value of five | |
cout << "5-- = " << five-- << endl; // decrement after getting value of five | |
cout << "--5 = " << --five << endl; // decrement before getting value of five | |
five += 6; // five becomes 11 | |
int eleven = five; | |
five = 5; // reassign five | |
bool isEqual = eleven == five + 6; | |
cout << "isEqual: " << isEqual << endl; // decrement before getting value of five | |
cout << "1 + 2 - 3 * 2 = " << 1 + 2 - 3 * 2 << endl; // multiplication occurs first | |
cout << "(1 + 2 - 3) * 2 = " << (1 + 2 - 3) * 2 << endl; | |
} | |
void learnCastType() { | |
/** CAST TYPE */ | |
cout << "\n:::: CAST TYPE ::::" << endl; | |
cout << "4 / 5 = " << 4 / 5 << endl; | |
cout << "(float)4 / 5 = " << (float)4 / 5 << endl; | |
} | |
void learnIf() { | |
/** IF STATEMENT */ | |
cout << "\n:::: IF STATEMENT ::::" << endl; | |
int age = 70; | |
int ageAtLastExam = 18; | |
bool correctVision = true; | |
if ((age >= 1) && (age < 16)) { | |
cout << "You can't drive" << endl; | |
} else if (!correctVision) { | |
cout << "Not sure you could drive" << endl; | |
} else if (age >= 80 && ((age > 100) || (age - ageAtLastExam) > 5)) { | |
cout << "You should pass an exam again" << endl; | |
} else { | |
cout << "Ok, you can drive" << endl; | |
} | |
} | |
void learnSwitch() { | |
/** SWITCH */ | |
cout << "\n:::: SWITCH ::::" << endl; | |
int greetingOpion = 2; | |
switch (greetingOpion) { | |
case 1: | |
cout << "Bonjour" << endl; | |
break; | |
case 2: | |
cout << "Hola" << endl; | |
break; | |
default: | |
cout << "Hello" << endl; | |
break; | |
} | |
} | |
void learnTernary() { | |
/** TERNARY OPERATOR */ | |
cout << "\n:::: TERNARY OPERATOR ::::" << endl; | |
int largestNum = (5 > 2) ? 5 : 2; | |
cout << "largestNum :" << largestNum << endl; | |
} | |
void learnArray() { | |
/** ARRAY */ | |
cout << "\n:::: ARRAY ::::" << endl; | |
int myFavNums[5]; | |
int badNums[5] = {20, 33, 57, 83, 91}; | |
cout << "Bad Number 1 :" << badNums[0] << endl; | |
char myName[4][5] = {{'A', 's', 't', 'e', 'n'}, {'M', 'i', 'e', 's'}}; // starts with last array definition | |
cout << "3rd letter in 2nd array: " << myName[1][2] << endl; // arrays start at index 0 | |
myName[1][2] = 'i'; // re-assign new value | |
cout << "3rd letter in 2nd array new value: " << myName[1][2] << endl; // arrays start at index 0 | |
myName[1][2] = 'e'; // re-assign new value | |
} | |
void learnFor() { | |
char myName[4][5] = {{'A', 's', 't', 'e', 'n'}, {'M', 'i', 'e', 's'}}; | |
/** FOR LOOPS */ | |
cout << "\n:::: FOR LOOPS ::::" << endl; | |
for (int i = 1; i <= 10; i++) { | |
cout << i << endl; | |
} | |
for (int j = 0; j < 4; j++) { | |
for (int k = 0; k < 5; k++) { | |
cout << myName[j][k]; | |
} | |
cout << endl; | |
} | |
} | |
void learnWhile() { | |
/** WHILE LOOPS */ // When you don't know when your loop will end ahead of time | |
cout << "\n:::: WHILE LOOPS ::::" << endl; | |
int randNum = (rand() % 100) + 1; // 0 - 99 so we add 1 to reach 100 | |
while (randNum != 100) { | |
cout << randNum << ","; | |
randNum = (rand() % 100) + 1; | |
} | |
cout << endl; | |
int index = 1; | |
while (index <= 10) { | |
cout << index << endl; | |
index++; | |
} | |
} | |
void learnDoWhile() { | |
/** DO WHILE LOOPS */ // To execute what is in a while loop at least one time even if the while condition is false | |
cout << "\n:::: DO WHILE LOOPS ::::" << endl; | |
string numberGuessed; | |
int intNumberGuessed = 0; | |
do { | |
cout << "Guess a number between 1 and 10: (4 is the answer) "; | |
// userinput-- getline(cin, numberGuessed); | |
if (numberGuessed.empty()) numberGuessed = "4"; | |
// stoi converts string to integer, stod converts string to double... | |
intNumberGuessed = stoi(numberGuessed); | |
cout << intNumberGuessed << endl; | |
} while (intNumberGuessed != 4); // winning number is 4 | |
cout << "Your win" << endl; | |
} | |
void learnString() { | |
/** STRING OBJECTS */ | |
cout << "\n:::: STRING OBJECTS ::::" << endl; | |
char happyArray[6] = {'H', 'a', 'p', 'p', 'y', '\0'}; // This is how to create a string in C | |
string birthdayString = " Birthday"; // This is how we create a string in C++ | |
cout << happyArray + birthdayString << endl; // Join strings with the concatenation operator | |
string yourName; | |
cout << "What is your name ? "; | |
// userinput-- getline(cin, yourName); // store user input in yourName, cin is the source input | |
if (yourName.empty()) yourName = "Asten Mies"; | |
cout << "Hello " << yourName << endl; | |
double eulersConstant = .57721; | |
string eulerGuess; | |
double eulerGuessDouble; | |
cout << "What is Euler's Constant ? "; | |
// userinput-- getline(cin, eulerGuess); | |
if (eulerGuess.empty()) eulerGuess = ".55"; | |
eulerGuessDouble = stod(eulerGuess); | |
if (eulerGuessDouble == eulersConstant) { | |
cout << "You are right" << endl; | |
} else { | |
cout << "You are wrong" << endl; | |
} | |
cout << "Size of string: " << eulerGuess.size() << endl; | |
cout << "Is string empty: " << eulerGuess.empty() << endl; | |
cout << eulerGuess.append(" was your guess") << endl; | |
// compare strings (alphabetical) | |
string dogString = "dog"; | |
string catString = "cat"; | |
cout << dogString.compare(catString) << endl; // 1 if it's less than | |
cout << dogString.compare(dogString) << endl; // returns 0 when equal | |
cout << catString.compare(dogString) << endl; // -1 if it's greater than | |
string wholeName = yourName.assign(yourName); // assign a new value | |
cout << wholeName << endl; | |
// https://youtu.be/Rub-JsjMhWY?t=1613 | |
// substring | |
string firstname; | |
firstname.assign(wholeName, 0, 5); // Get whole name from char 0 for length of 5 | |
cout << "Substring: " << firstname << endl; | |
// find substring in string | |
int lastNameIndex = wholeName.find("Mies", 0); // Start searching for that string at index 0 | |
string lastName; | |
lastName.assign(wholeName, lastNameIndex); | |
cout << "Find in string: " << lastName << endl; | |
// insert in string (index, substring) | |
yourName.insert(5, " Bob"); | |
cout << "Insert in string: " << yourName << endl; | |
// delete from string (index, length) | |
yourName.erase(6, 4); | |
cout << "Erase from string: " << yourName << endl; | |
// replace in string (index, length) | |
yourName.replace(0, 5, "Bobby"); | |
cout << "Replace in string: " << yourName << endl; | |
} | |
void learnVector() { | |
/** VECTOR */ // Same as arrays but size can change | |
cout << "\n:::: VECTOR ::::" << endl; | |
vector<int> lotteryNumVect(10); | |
int lotteryNumArray[5] = {4, 13, 14, 25, 66}; | |
lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, | |
lotteryNumArray + 3); // (from begin, array to insert, length of the part we want to insert) | |
cout << "Insert in vector: " << lotteryNumVect.at(2) << endl; | |
lotteryNumVect.insert(lotteryNumVect.begin() + 5, 44); // starts at index 5 | |
cout << "Insert in vector: " << lotteryNumVect.at(5) << endl; // outputs the one that we just inserted at index 5 | |
lotteryNumVect.push_back(64); // push from the back | |
cout << "First value in vector: " << lotteryNumVect.front() << endl; | |
cout << "Final value in vector: " << lotteryNumVect.back() << endl; | |
cout << "Vector size: " << lotteryNumVect.size() << endl; | |
} | |
/** SEE FUNCTIONS CHAPTER */ | |
int addNumbers(int firstNum, int secondNum = 0) { | |
int combinedValue = firstNum + secondNum; | |
return combinedValue; | |
} | |
// We can overload a function (already defined but re-defining) | |
int addNumbers(int firstNum, int secondNum, int thirdNum) { | |
int combinedValue = firstNum + secondNum + thirdNum; | |
return combinedValue; | |
} | |
int getFactorial(int number) { | |
int sum; | |
if (number == 1) | |
sum = 1; | |
else | |
sum = getFactorial(number - 1) * number; | |
return sum; | |
} | |
void learnFunction() { | |
/** FUNCTIONS */ | |
cout << "\n:::: FUNCTIONS (see top of file) ::::" << endl; | |
cout << "Call function addNumbers: " << addNumbers(1) << endl; | |
cout << "Call function addNumbers: " << addNumbers(1, 5, 6) << endl; | |
cout << "Call function getFactorial of 3: " << getFactorial(3) << endl; | |
} | |
int learnFile() { | |
/** FILES */ | |
cout << "\n:::: FILES (read and write) ::::" << endl; | |
string steveQuote = "A day without sunshine is like, you know, night"; | |
ofstream writer("stevequote.txt"); | |
if (!writer) { | |
cout << "Error opening file" << endl; | |
return -1; | |
} else { | |
writer << steveQuote << endl; // create file was successful? Write into it | |
} | |
ofstream writer2("stevequote.txt", ios::app); // append to then end of file | |
// ios::binary : Treat the file as binary | |
// ios::in : Open a file to read input | |
// ios::truc : Default | |
// ios::out : Open a file to write output | |
if (!writer2) { | |
cout << "Error opening file" << endl; | |
return -1; | |
} else { | |
writer2 << "\n - Steve Martin" << endl; // create file was successful? Write into it | |
} | |
char letter; // will hold each character | |
ifstream reader("stevequote.txt"); | |
if (!reader) { | |
cout << "Error opening file" << endl; | |
return -1; | |
} else { // stream is open | |
// Read each character from the stream until the end of the file | |
for (int i = 0; !reader.eof(); i++) { | |
reader.get(letter); | |
cout << letter; | |
} | |
cout << endl; | |
reader.close(); | |
} | |
} | |
void learnException() { | |
/** EXCEPTION HANDLING */ | |
cout << "\n:::: EXCEPTION HANDLING ::::" << endl; | |
// division by 0 error | |
int number = 0; | |
// Instead of causing an error, with a try block we can catch it and throw a message | |
try { | |
if (number != 0) { | |
cout << 2 / number << endl; | |
} else | |
throw(number); // throw is looking for a catch. | |
} catch (int number) { | |
cout << number << " is not valid" << endl; | |
} | |
} | |
/** SEE POINTERS CHAPTER */ | |
void makeMeYoung(int* age) { | |
cout << "I used to be " << *age << endl; | |
*age = 21; | |
} | |
void actYourAge(int& age) { age = 42; } | |
void learnPointer() { | |
/** POINTERS */ // Memory addresses | |
cout << "\n:::: POINTERS ::::" << endl; | |
int myAge = 30; | |
char myGrade2 = 'A'; | |
cout << "Size of int: " << sizeof(myAge) << endl; // 4 bytes | |
cout << "Size of char: " << sizeof(myAge) << endl; // 1 byte | |
// reference this box / memory address with the reference operator & | |
cout << "myAge is located at " << &myAge << endl; // outputs the memory address example: 0x7ffccc557780 | |
// if we don't use pointers or we don't use reference operators | |
// and we change the value of a variable in a function | |
// that change of value does not carry on - it is lost | |
int* agePtr = &myAge; // pass that memory address over to our pointer | |
cout << "Address of pointer: " << agePtr << endl; | |
cout << "Data at memory address: " << *agePtr << endl; // de-reference to get the data at that memory address | |
int badNums2[5] = {20, 33, 57, 83, 91}; | |
int* numArrayPtr = badNums2; // create a pointer | |
cout << "Address " << numArrayPtr << " Value " << *numArrayPtr << endl; | |
numArrayPtr++; // goes one integer further, so 4 bytes more in the address | |
cout << "Next Address " << numArrayPtr << " Value " << *numArrayPtr << endl; | |
// PASSING BY POINTER | |
// Use pointer when you don't want to initialize at declaration | |
// means I can (re-)initialize later | |
makeMeYoung(&myAge); // modify the value through a function | |
cout << "I'm " << myAge << " years old now" << endl; | |
int& ageRef = myAge; | |
cout << "myAge: " << myAge << endl; | |
ageRef++; | |
cout << "myAge: " << myAge << endl; | |
// PASSING BY REFERENCE | |
// When ok to initialize at declaration | |
// not able to change whatever you're pointing at after that | |
actYourAge(ageRef); | |
cout << "myAge: " << myAge << endl; | |
} | |
/** SEE CLASS CHAPTER */ | |
class Animal { | |
// Attributes : height weight modeled in variable | |
// Capabilities : Run Eat modeled in methods | |
private: // can only be changed by functions inside this class - called encapsulation | |
int height; | |
int weight; | |
string name; | |
static int numOfAnimals; // is going to be shared by every object of type animal that is going to be created | |
public: // to be able to access the private values - we encapsulate them to keep them protected | |
int getHeight() { return height; } | |
int getWeight() { return weight; } | |
string getName() { return name; } | |
// protect the values that are going to be stored | |
void setHeight(int cm) { height = cm; }; | |
void setWeight(int kg) { weight = kg; }; | |
void setName(string animalName) { name = animalName; }; | |
// we declare a prototype of a function | |
void setAll(int, int, string); | |
// a constructor - handle creating every object | |
Animal(int, int, string); | |
// a destructor | |
~Animal(); | |
// overloading - a constructor that doesn't receive anything. Should have no arguments | |
Animal(); | |
// static method | |
static int getNumberOfAnimals() { return numOfAnimals; }; | |
void toString(); | |
}; | |
// declare our static | |
int Animal::numOfAnimals = 0; | |
void Animal::setAll(int height, int weight, string name) { | |
// no animals created yet | |
this->height = height; | |
this->weight = weight; | |
this->name = name; | |
Animal::numOfAnimals++; | |
} | |
// constructor | |
Animal::Animal(int height, int weight, string name) { | |
this->height = height; | |
this->weight = weight; | |
this->name = name; | |
Animal::numOfAnimals++; | |
} | |
Animal::~Animal() { cout << "Animal " << this->name << " destroyed" << endl; } | |
Animal::Animal() { Animal::numOfAnimals++; } | |
void Animal::toString() { | |
cout << this->name << " is " << this->height << " cms tall and " << this->weight << " kgs in weight " << endl; | |
} | |
void learnClass() { | |
/** CLASS */ | |
cout << "\n:::: CLASS ::::" << endl; | |
Animal fred; | |
fred.setHeight(33); | |
fred.setWeight(10); | |
fred.setName("Fred"); | |
cout << fred.getName() << " is " << fred.getHeight() << " cms tall and " << fred.getWeight() << " kgs in weight " | |
<< endl; | |
Animal tom(12, 1, "Tom"); | |
cout << tom.getName() << " is " << tom.getHeight() << " cms tall and " << tom.getWeight() << " kgs in weight " | |
<< endl; | |
} | |
int main() { | |
cout << "Hello" << endl; | |
learnTypesAndSize(); | |
learnMath(); | |
learnCastType(); | |
/** COMPARISON OPERATORS: ==, !=, >, <, >=, <= */ | |
/** LOGICAL OPERATORS: && || ! */ | |
learnIf(); | |
learnSwitch(); | |
learnTernary(); | |
learnArray(); | |
learnFor(); | |
learnWhile(); | |
learnDoWhile(); | |
learnString(); | |
learnVector(); | |
learnFunction(); | |
learnFile(); | |
learnException(); | |
learnPointer(); | |
learnClass(); | |
return 0; | |
} |