Every program starts in main, and console I/O is how you try out everything else in this course.
A C++ program starts in main. It returns an int to the operating system: 0 means success, anything else signals failure. main is the one function where you may leave out the return; reaching the closing brace returns 0.
Standard library names live in the namespace std, so you write std::cout, std::string and so on. You get them by including headers: <iostream> for console streams, <string> for strings.
std::cout << xwrites to standard output.<<returns the stream, so calls chain:std::cout << "a" << 1 << '\n';.std::cerris standard error, for diagnostics.std::cin >> xreads one whitespace-separated value and converts it to the type ofx. The expression is false if reading failed, so test it.std::getline(std::cin, s)reads a whole line, spaces included.
Prefer '\n' over std::endl: endl also flushes the buffer, which is slow in loops. A classic gotcha is mixing >> and getline: after std::cin >> n the newline is still waiting in the input, so the next getline returns an empty line.
C++20 added std::format (header <format>) for Python-style formatting, std::format("{} is {}", name, age), and C++23 adds std::println in <print>, which formats and prints in one call. Streams are still everywhere in existing code, so learn both.
Avoid using namespace std; at file scope in real projects; it pulls hundreds of names into scope and causes clashes. Writing std:: is the norm.
Example
#include <iostream>
#include <string>
int main() {
std::cout << "What's your name? ";
std::string name;
std::getline(std::cin, name); // whole line, spaces included
std::cout << "Hello, " << name << "!\n";
int a = 0, b = 0;
std::cout << "Two numbers: ";
if (std::cin >> a >> b) { // false if the input wasn't numbers
std::cout << a << " + " << b << " = " << a + b << '\n';
} else {
std::cerr << "That was not a number\n";
return 1; // non-zero: failure
}
} // falling off the end of main returns 0Remember
mainreturnsint; 0 means success<<writes,>>reads one token,std::getlinereads a line- Use
'\n'instead ofstd::endlunless you really need a flush - C++20
std::formatand C++23std::printlnare the modern formatting tools
Watch out for
- Calling
std::getlineright afterstd::cin >> nand getting an empty string because the newline was left in the input.