Useful methods, basic libraries, and multiple file projects
A library is a collection of related modules that provides reusable functionality to simplify development. To add a library to our program, we use the #include
command, e.g., #include <iostream>
.
Files
In a project, we can create multiple files to separate functionalities, improving code organization. Header files (.h
) are used to declare variables, functions, and classes that can be shared across multiple files./p>
library.h
The #include "library.h"
line imports everything from library.h
into the current file. If <iostream>
is included in library.h
, there is no need to include it again, as it will be carried over automatically. To prevent errors caused by multiple inclusions of the same file, we use preprocessor directives such as #ifndef LIBRARY
. These safeguards ensure that the file is included only once, a feature that built-in libraries already handle internally.
#include <iostream>
using namespace std;
#ifndef _LIBRARY // this name has to match the file name
#define _LIBRARY 1
int x = 10;
void display() {
cout << x << endl;
}
#endif
main.cpp
#include "library.h"
int main(int argc, char *argv[]) {
cout << x << endl;
display();
x = 1;
cout << x << endl;
display();
return 0;
}
Useful methods
stoi()
// String to integer
string x = "1";
int y = stoi(x);
cout << y << endl;
length()
// A number of characters in a string (its length)
string x = "abcd";
cout << x.length() << endl;
substring()
// Extracting a substring from a string
string str = "Hello World!";
string sub = str.substr(6, 5); // (starting index, length)
cout << sub << endl;
find()
// Finding the position of the first occurrence of a substring in a string (the index of the substring's first letter). If there are more than one - the index of the first one encountered.
string str = "Hello World!";
int pos = str.find("World");
if (pos != string::npos) // checking if the substring was found (find() returns string::npos if not found)
cout << "Found at position: " << pos << endl;
else
cout << "Not found" << endl;
abs()
- the <cmath>
library
// An absolute value of a number
int x = -4;
cout << abs(x) << endl;
sqrt()
- the <cmath>
library
// The square root of a number
int x = 4;
cout << sqrt(x) << endl;
exit()
- the <cstdlib>
library
// Ending the program
exit(0);
cout << "This won't be displayed." << endl;
Sleep()
- the <windows.h>
library
// Stopping the program for a time specified in miliseconds
Sleep(1000);
system("cls")
- the <cstdlib>
library
// Clearing the console
cout << "This won't be displayed." << endl;
system("cls");
Reversing a string - the <algorithm>
library
string str = "CPUcademy";
reverse(str.begin(), str.end());
cout << str << endl;