Você está na página 1de 6

C++ Notes

Headers
#include
#include
#include
#include
#include
#include

<iostream> //for stream IO


<algorithm> //for algorithms implemented in the library
<time.h> //for time related functions
<fstream> //for file IO
<vector> //for vector functions
<string> //for STL string functions

Working with STL Strings


//Unlike character arrays STL strings can hold strings of any length.
int intNumberGuessed = 0;
string numberGuessed;
do {
cout << "Guess a number between 1 and 10" << endl;
getline(cin, numberGuessed); /*The getline function gets a string from the user
(std input) and puts it in the string numberGuessed.*/
intNumberGuessed = stoi(numberGuessed); //stoi = string to integer
} while (intNumberGuessed != 4);
double eulerConstant = 0.57721;
string eulerGuess;
double yourGuess = 0;
cout << "Guess the Euler Constant." << endl;
getline(cin, eulerGuess);
yourGuess = stod(eulerGuess); //convert string to double
if (yourGuess == eulerConstant)
cout << "You are right" << endl;
else
cout << "You are wrong" << endl;
cout << "Size of the answer: " << eulerGuess.size() << endl; //This returns the size of the
string

cout << "Is your string empty: " << eulerGuess.empty() << endl; //This returns 0 if the
string is not empty
cout << eulerGuess.append(" was your guess") << endl; //This appends the literal to the
string.
string dog = "dog"; //using single quotes to initialise a string generates a compiler error.
string cat = "cat";
cout << dog.compare(cat) << endl; //Compares two strings. Returns 1 since c > d.
cout << cat.compare(cat) << endl; //Compares two strings. Returns 0 since c = c.
cout << cat.compare(dog) << endl; //Compares two strings. Returns -1 since c < d.
//copy one string into another
string yourName = "Ratnadeep";
string myName = yourName.assign(yourName);
cout << myName << endl;
//substrings
string shortName = myName.assign(myName, 0, 5); //copy 5 characters starting from
index 0 into the string 'name'.
cout << shortName << endl;

//pattern matching
string petName = "deep";
int indexPetName = (int)yourName.find(petName, 0); /*returns the correct index in this
case. However, if myName is used then it returns -1. The find op returns type size_t. It can be
cast to int to stop the compiler from complaining.*/
cout << indexPetName << endl;
/*Adding, erasing and replacing from strings. The following changes do not copy the value
of the string to another temporary variable. They change the variable in place. So the changes
are permanent.*/
cout << myName.insert(1, "D") << endl;
cout << myName.erase(1, 5) << endl;
cout << myName.replace(0, 10, "RD") << endl;
wstring nameWide = L"This is a wide string"; //Wide Strings. The L has to be there.
cout << nameWide.length() << endl; // Checking length of the string.
Vectors
//Talking about vectors. Their size can change. Otherwise they are just like arrays.
vector <int> lotteryNumVect(10); //int is the data type that the vector holds and 10 is the
initial size.
int lotteryNumArray[5] = { 4, 3, 8, 10, 45 };//We will change this array into a vector.
lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, lotteryNumArray + 3);
/*The first argument tells where we want to start inserting the data. The second argument says
from where (array name is also a pointer). The third argument says how many elements we want
to put into the vector.*/
cout << lotteryNumVect.at(2) << endl; //print the third element (second index) in the
vector.
lotteryNumVect.insert(lotteryNumVect.begin() + 5, 44); //Inserting 44 at the 5th index of
lotteryNumVect.
cout << lotteryNumVect.at(4) << " " << lotteryNumVect.at(5) << endl; /*The indexes
of the vector that are not explicitly populated have a 0 in them. However, this is possibly a
compiler behavior.*/
lotteryNumVect.push_back(64); //This resizes the vector and puts 64 at the end.
cout << "The final value is: " << lotteryNumVect.back() << endl;
lotteryNumVect.pop_back(); //This removes the last value.
cout << "The final value is: " << lotteryNumVect.back() << endl;
cout << "The first value is: " << lotteryNumVect.front() << endl; //This gets the first
value in the vector.
cout << "Is the vector empty: " << lotteryNumVect.empty() << endl; //Returns 0 if the
vector is empty, 1 if it is not.
cout << "The size of the vector is: " << lotteryNumVect.size() << endl; //Returns the size
of the vector
Function Calls
Prototyping
//Functions in C++
int addNumbers(int firstNum, int secondNum = 0); /*In this case we pre-define the second
variable in the prototype. This is because, otherwise the compiler does not know what to do with
a call to addNumbers() that takes 1 argument.*/
int addNumbers(int firstNum, int secondNum, int thirdNum);
//Function using pointers

void changeMyAge(int* age){ *age = 39; }

Main
//Function calls
cout << addNumbers(1) << endl; //This uses the function with two arguments where
secondNum = 0.
cout << addNumbers(1, 2, 3) << endl; //This uses the function with three arguments.
cout << addNumbers(1, 2) << endl; /*This uses the function with 2 arguments. But since
a second argument has also been provided, secondNum != 0 anymore but secondNum = 2.*/
//Functions using pointers
int myAge = 32;
cout << "My age is " << myAge << endl;
changeMyAge(&myAge); //passing the pointer of myAge to the function changeMyAge
cout << "My age is " << myAge << endl;
Function definition
//Functions in C++
int addNumbers(int firstNum, int secondNum){ /*In the function definition the second number is
not explicitly defined. If we define the second number again, then the compiler gets confused
because it has already been defined in the prototype.*/
return firstNum + secondNum;
}
int addNumbers(int firstNum, int secondNum, int thirdNum){
return firstNum + secondNum + thirdNum;
}
File IO
string BoseQuote = "Give me blood and I will give you freedom.";
ofstream writer("F:\\Studies\\Programming Projects\\C++ Projects\\Test\\BoseQuote.txt");
if (!writer){
cout << "Error opening file" << endl;
return -1;
}
else {
writer << BoseQuote << endl;
writer.close();
}
ofstream writer2("F:\\Studies\\Programming Projects\\C++ Projects\\Test\\BoseQuote.txt",
ios::app);
/*ios::app to append to the end of the file.
ios::binary treat the file as a binary
ios::in open a file to read
ios::trunc is the default
ios::out open a file to write output.*/
if (!writer2){
cout << "Error opening file" << endl;
return -1;
}
else {
writer2 << "\n - Netaji Subhash Chandra Bose" << endl;
writer2.close();
}
char letter;

ifstream reader("F:\\Studies\\Programming Projects\\C++ Projects\\Test\\BoseQuote.txt");


if (!reader)
{
cout << "Error reading from file" << endl;
return -1;
}
else
{
for (int i = 0; !reader.eof(); i++)
{
reader.get(letter);
cout << letter;
}
cout << endl;
reader.close();

Exception Handling
int num = 0;
try {

if (num != 0)
cout << 2 / num << endl;
else throw(num); //Throw looks for a catch statement.

catch (int num){


cout << num << " is not valid." << endl;

Working with classes


//Defining a class
class Animal {
//Attributes: height weight - modeled in variables
//Capabilities: Run Eat - modeled in functions and methods
private: //private variables can be changed only by functions inside the class - this is called
Encapsulation.
int height, weight;
string name;
static int numOfAnimals; //Static variables are ones that are shared by all the objects of
type Animal.
public:
int getHeight(){ return height; }
int getWeight(){ return weight; }
string getName(){ return name; }
void setHeight(int height){ this->height = height; }
void setWeight(int weight){ this->weight = weight; }
void setName(string name){ this->name = name; }
Animal(int, int, string); //constructor prototype
~Animal(); //destructor prototype

Animal(); //overloaded constructor prototype


static int getNumOfAnimals(){ return numOfAnimals; } /*They are attached to the class
and not the objects. Static methods can call only static variables.*/
void toString();
};
//defining the class functions and initialising static variables
int Animal::numOfAnimals = 0;
Animal::Animal(int height, int weight, string name){
/*The pointer this points to the particular object which has called the function. So the
value passed as height should be set to height of this animal's height and so on.*/
this->height = height;
this->weight = weight;
this->name = name;
Animal::numOfAnimals++;
}
Animal::~Animal(){
cout << "Animal " << this->name << " is destroyed" << endl;
Animal::numOfAnimals--;
}
Animal::Animal() : height(10), weight(15), name("General") //Using initialisation list
{
Animal::numOfAnimals++;
}
void Animal::toString(){
cout << this->name << " is " << this->height << " cm tall and weighs " << this>weight << " kgs." << endl;
}
//Inheritance
class Dog :public Animal{ //The Dog class inherits from the Animal class with the single colon
private:
string sound = "woof";
public:
void getSound(){ cout << sound << endl; }

};

Dog(int, int, string, string);


Dog();
void toString();

//Defining the functions in the inheritance class


Dog::Dog(int height, int weight, string name, string sound) :Animal(height, weight, name){/*Here
the Dog class constructor lets the Animal class constructor handle the initialisation of height,
weight and name. The Dog class constructor specifically handles only the sound part.*/
this->sound = sound;
}
void Dog::toString(){
cout << this->getName() << " is " << this->getHeight() << " cm tall, weighs " << this>getWeight() << " and says " <<
this->sound << endl;

}
//Creating Animal class objects
Animal fred;
fred.setHeight(33);
fred.setWeight(10);
fred.setName("Fred");
Animal *shark = new Animal(); //shark is an Animal type created in the heap and uses the
default constructor.
cout << shark->getName() << " is " << shark->getHeight() << " cm tall and weighs "
<< shark->getWeight() << endl;
delete shark; /*Shark needs to be explicitly deleted. The deconstructor is not called, which
is the biggest disadvantage of using objects in heap.*/
cout << fred.getName() << " is " << fred.getHeight() << " cm tall and weighs " <<
fred.getWeight() << " kgs." << endl;
Animal tom(35, 12, "Tom");
cout << tom.getName() << " is " << tom.getHeight() << " cm tall and weighs " <<
tom.getWeight() << " kgs." << endl;
//Inheritance (Creating Dog class object)
Dog spot(33, 16, "Spot", "Woof");
cout << "Number of Animals created: " << Animal::getNumOfAnimals() << endl;
spot.getSound();
tom.toString();
spot.toString();
spot.Animal::toString(); //Calling the animal version of toString() on spot

Você também pode gostar