main is the entry point; std::cin and std::cout read and write through type-safe streams with >> and <<.
Anatomy of a program
#include <iostream> // std::cin, std::cout, std::cerr
#include <string> // std::string
int main() {
std::string name;
int age;
std::cin >> name >> age; // whitespace-separated tokens
std::cout << "Hi " << name << ", next year you'll be " << age + 1 << ".\n";
}Hi Asha, next year you'll be 25.| Stream | Purpose | Buffered? |
|---|---|---|
std::cout | Standard output | Yes |
std::cin | Standard input | Yes |
std::cerr | Error output (unbuffered — shows up immediately) | No |
std::clog | Log output to stderr | Yes |
main signatures
#include <iostream>
int main(int argc, char* argv[]) { // argc = number of args, argv[0] = program name
std::cout << "args: " << argc - 1 << '\n';
for (int i = 1; i < argc; ++i) std::cout << i << ": " << argv[i] << '\n';
return 0; // 0 = success; non-zero = failure
}args: 2
1: build
2: --fastReading lines with getline
>> stops at whitespace. To read a whole line use std::getline. After a >>, the newline is still in the buffer — skip it with std::ws (or cin.ignore()) first.
#include <iostream>
#include <string>
int main() {
int id;
std::string fullName;
std::cin >> id;
std::getline(std::cin >> std::ws, fullName); // std::ws eats the leftover '\n'
std::cout << id << " -> [" << fullName << "]\n";
}7 -> [Ada Lovelace]Reading until end of input
#include <iostream>
int main() {
long long sum = 0;
int x;
while (std::cin >> x) sum += x; // the stream converts to false at EOF or bad input
std::cout << "sum = " << sum << '\n';
}sum = 22\n vs std::endl
using namespace std;
Everything in the standard library lives in namespace std. Writing using namespace std; saves typing in small programs and contest code, but in headers or large code bases it pulls hundreds of names into scope and causes clashes (std::count, std::distance, std::size…).
What does std::cin >> x return, and why can it be used in a while condition?