Step 1 of 7
Hello, C++
Welcome to C++. Bjarne Stroustrup started it in 1979 as "C with Classes" and renamed it C++ in 1983, and almost everything you learned in C still works: variables, if, loops, functions, pointers, arrays and structs. What C++ adds are tools that make programs safer and shorter: classes that clean up after themselves, a huge standard library (strings, dynamic arrays, maps, algorithms), references, templates and more.
The first difference you'll notice is output. Instead of printf with format specifiers, C++ uses streams:
#include <iostream>
int main() {
int kills = 25;
double accuracy = 0.61;
std::cout << "Kills: " << kills << "\n";
std::cout << "Accuracy: " << accuracy << " (" << accuracy * 100 << "%)\n";
}
Kills: 25
Accuracy: 0.61 (61%)
How it works
#include <iostream>brings in the stream library (C++ standard headers have no.h).std::coutis the standard output stream, the C++ equivalent ofstdout.<<sends a value into the stream. Expressions chain from left to right: each<<returns the stream again, so the next<<continues writing.- There are no format specifiers. The compiler knows each value's type and picks the right way to print it, so the classic
printfmismatch bugs can't happen. std::is a namespace prefix: the standard library's names live in the namespacestd, so they don't clash with your own names.- In C++,
mainmay leave outreturn 0;; reaching the end ofmainmeans success.
You'll see std::endl in older code; it prints a newline and flushes the stream, which is slower. "\n" is usually what you want.
Your turn: print Rounds won: 13 using cout.