3. Inputs, Outputs and Comments

Remember the library iostream? We included it so “Hello World” could print successfully. Try deleting it for a second and running the code to see what happens - you should obtain an error. Inputs and outputs (like “Hello World”) are very important in C++ as you can interact with the user (get information from it and tell the user information). For example, you can tell C++ to take in some data or numbers from the user (input), tell C++ to perform some complicated calculations, and then print out the final answer for the user to see (output).


Input and output (IO) in C++ is based on the concept of streams. Streams are sequences of bytes that flow in and out of programs similar to the way water flows through a pipe. Input works by allowing data to flow into a program from an input source such as your keyboard or another file. Output does the opposite - data from your program flows out to an output sink, which could be the console or a file. In C++, we use the operators >> and << along with the statements cin and cout to receive and send data between the standard console and a program. The direction of a pair of angle brackets denotes a flow of information. Always point towards cout and away from cin

In the example above, which is a variation on the Hello World code you saw earlier, both cin and cout are used. You can ignore how the other parts of the program that you don’t recognize work for now, just focus on the cin and cout statements. The program first outputs a statement (using cout) to ask you to enter your first name. Try this code yourself to see exactly how this works. Enter your name in the console when it prompts you to do so. Did the console display “Hello <your name>”? After asking you to enter your name by using cout, the program takes your name as an input and saves it to a variable called name (we will discuss variables in the following section). This is done through the cin command. Finally, the program uses cout once again to output “Hello ” and then your name. The >> operator is used in conjunction with cin and << with cout.

You may be wondering what endl means. This tells the program to start a new line in the console, otherwise “Enter your first name: <your name>” and “Hello <your name>” would be on the same line instead of seperate ones. Be aware, endl stands for end line. It is a lowercase L not a 1.


One other important note before you embark on your journey of learning C++:

Semicolons in C++ play a similar role to periods in English. Just like how we use periods to mark the end of each of our sentences, semicolons are used after most statements in C++ to indicate the termination of the statement. Always check to make sure you’ve included your semicolons! One of the most common errors you will come across when learning C++ will be forgetting to include one of these somewhere.