main, cout and cin
Every C++ program starts in main. To talk to the outside world you include <iostream>, which gives you three stream objects: std::cout (standard output), std::cin (standard input) and std::cerr (error output). You push values into an output stream with << and pull values out of an input stream with >>. The arrows point the way the data flows.
#include <iostream>
int main() {
std::cout << "Order summary\n";
std::cout << "Items: " << 3 << ", total: " << 59.5 << '\n';
// Chaining works because each << returns the stream itself
std::cout << "A" << 'B' << 1 << true << '\n';
std::cerr << "(this line goes to standard error)\n";
return 0;
}Order summary
Items: 3, total: 59.5
AB11The std::cerr line is not in the output above: it goes to a separate stream (standard error) that the terminal shows but a > file.txt redirect does not capture. true prints as 1 unless you stream std::boolalpha first.
Add std::cout << std::boolalpha << true << '\n'; and see it print true instead of 1.
Reading input with cin
std::cin >> x skips any leading whitespace, then reads characters until they stop making sense for the type of x. So reading into a std::string stops at the first space: it reads one word, not a line. The example below is fed the input Asha 29.
#include <iostream>
#include <string>
int main() {
std::string name;
int age = 0;
std::cout << "Name and age: ";
std::cin >> name >> age; // reads "Asha", then 29
std::cout << '\n' << name << " will be " << age + 1 << " next year\n";
}Name and age:
Asha will be 30 next yearRun it yourself and type a word instead of the age. age stays 0 because the read failed; check if (!std::cin) after reading to detect it.
'\n'
- Ends the line. That is all.
- Output is buffered and written in large, cheap chunks.
- Use it by default.
std::endl
- Ends the line and flushes the buffer to the device.
- A flush is a system call; in a loop of a million lines it can make output several times slower.
- Use it only when the text must appear right now (for example before a long computation or a crash).
Comments
// text comments to the end of the line; /* text */ can span lines but cannot be nested. Comment why, not what: i++; // add one to i tells the reader nothing, while // retry once: the first request after wake-up often times out saves the next person an hour.
