$ g++ greet.cpp -o greet$ ./greetName? Name? AdaHi, Ada!$ echo $?0$ ./greetName? Ada LovelaceHi, Ada!Name? AName? AdHi, Hi, AdaName? Name? AName? AdName? AdaName? Ada Name? Ada LName? Ada LoName? Ada LovName? Ada LoveName? Ada LovelName? Ada LovelaName? Ada Lovelac1#include <iostream>2#include <string>3int main() {4 std::string name;5 std::cout << "Name? ";6 std::cin >> name;7 std::cout << "Hi, " << name;8 std::cout << "!\n";9 return 0;10}std::string name""Name?AdaHi,Ada!0Lovelace
Violet card: the program's ten lines; the yellow bar marks the line that runsSlate box: the variable name in memory; mint: the screen and keyboardTokens: text hopping to the screen, your typing hopping into the boxIn front: the source file greet.cpp and one box in memory, the variable name. At the back: the terminal's screen and keyboard. The program runs one line at a time: line 4 makes the empty box, line 5 puts Name? on the screen, line 6 copies the typed word Ada into the box, and lines 7 and 8 print Hi, then a copy of the box's value, then !. return 0 ends main and reports success. Typed with a space, Ada Lovelace puts only Ada in the box: >> reads one word. In main, and only in main, return 0; may be left out: reaching the closing } of main returns 0 anyway. Writing it makes the success visible.

The code

  1. This is a whole C++ program in one file, greet.cpp. It asks for your name, waits for you to type it, then greets you. It runs from top to bottom, one line at a time.

Running it line by line

A surprise

What happens

;; step 1/9 · program
greet.cpp
 1  #include <iostream>
 2  #include <string>
 3  int main() {
 4    std::string name;
 5    std::cout << "Name? ";
 6    std::cin >> name;
 7    std::cout << "Hi, " << name;
 8    std::cout << "!\n";
 9    return 0;
10  }
a statement is one instruction; most end with ;

g++ greet.cpp -o greet builds the program in one command (the preprocessor, compiler and linker run in turn). Adding -std=c++20 -Wall -Wextra picks the C++20 rules and turns on helpful warnings; this program builds with no warnings either way. With Clang, type clang++ instead of g++. std::cin >> name first skips any spaces, tabs or new lines, then reads characters up to the next one. The rest stays in the input, where the next read would find it. std::getline reads up to the end of the line instead.