Skip to content
  • Program Structure & I/O Streams · C++

Program Structure & I/O Streams

LearnViaNotes @learnvianotes· 3 min read

main is the entry point; std::cin and std::cout read and write through type-safe streams with >> and <<.

Anatomy of a program

C++
#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";
}
Output
Hi Asha, next year you'll be 25.
StreamPurposeBuffered?
std::coutStandard outputYes
std::cinStandard inputYes
std::cerrError output (unbuffered — shows up immediately)No
std::clogLog output to stderrYes

main signatures

C++
#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
}
Output
args: 2
1: build
2: --fast

Reading 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.

C++
#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";
}
Output
7 -> [Ada Lovelace]

Reading until end of input

C++
#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';
}
Output
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?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report