Loading

C++: Basic Input and Output

Basic Input and Output

This lesson covers a bit of input and output that will be essential for getting simple programs to work in C++. The material should cover the basics of what we will need for input and output for quite a few lessons.


As is customary, we start with a "Hello World!" program like the one we created in lesson 1. The original "Hello World" program came from C, and was programmed in the 1970's by Brian Kernighan. Since then, the use of "Hello World!" as a first example program has become the de facto standard first program in every language.

#include <iostream>

int main() {
    std::cout << "Hello World!" << std::endl;
    return 0;
}

The first "#include" statement pastes a code file into this one that gives us access to the input and output objects that we will use. The main function is used for all C++ console programs and it contains the code that will be executed. In this program, "std::cout" starts our only real line of code.

The statement "cout" is pronounced c-out, and it is the standard output stream for C++. When we execute the program by pressing "CTRL and "F5," this statement sends our "Hello World!" message to the console window, which looks like this:

Console Window

This window displays the output from the execution of our program. If we zoom in on the upper-left corner, we see that it displays "Hello World!"

Example 1 Output

One final remark before we move on, "endl" stand for endline, which returns to the beginning of the next line and is equivalent to pressing the "Enter" key in a text editor.


The last example demonstrated output. In this one, we demonstrate the use of input as well. To execute this code, create a new project like we did in lesson 1 and put the code below in the file main.cpp. Otherwise, you can just paste the code below over the "Hello World!" program code and reuse the previous project.

#include <iostream>

int main() {
    int iAge;
    std::cout << "How old are you?" << std::endl;
    std::cin >> iAge;
    std::cout << "You are " << iAge << " years old." << std::endl;
    return 0;
}

In this program, we introduce a variable "iAge" which holds an integer. This integer is where we will store the input. The statement "cin" is pronounced c-in, and it is the standard input stream for C++. The statement "cin" takes input from the console window. Here's the execution:

Example 2 Output

As the execution begins, the question "How old are you?" is sent to the console window to prompt the user for input. The c-in statement halts execution until the user types a number and then presses "Enter." The last c-out statement outputs the last line of text which includes the "iAge" variable.