Introduction to C++
Hello, world!
C is also valid C++ code:
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
but we can also use C++ features:
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
}
Header Files
We can use C header files in C++ but there are often C++ versions of the same. For example, we can find the length of a string like so:
#include <string>
#include <iostream>
int main() {
std::string hello = "hello";
int x = hello.size();
std::cout << hello << " is of length " << x;
}
In C you would use strlen()
.
Namespaces
Namespaces are like packages, for example:
std::cout
means that cout
is defined inn the std
namespace.
We can set a default namespace like so:
#include <string.h>
#include <iostream>
using namespace std;
int main() {
string hello = "hello";
int x = hello.length();
cout << hello << " is of length " << x;
}
This saves us writing std::
all the time.
Input Syntax
We can use something like the following to read input:
#include <iostream>
int main() {
std::string bla;
int num;
std::cin >> num >> bla;
std::cout << bla << " " << num;
}
This can work with integers and strings, and reads up to the first space for each variable.