Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Basic Input Using std::cin and Output Using std::cout

Your computer enables you to interact with applications running on it in various forms and allows these applications to interact with you in many forms, too. You can interact with applications using the keyboard or the mouse. You can have information displayed on the screen as text, displayed in the form of complex graphics, printed on paper using a printer, or simply saved to the file system for later usage. This section discusses the very simplest form of input and output in C++—using the console to write and read information.

You use std::cout (pronounced “standard see-out”) to write simple text data to the console and use std::cin (“standard see-in”) to read text and numbers (entered using the keyboard) from the console. In fact, in displaying “Hello World” on the screen, you have already encountered cout, as seen in Listing 2.1:

8:    std::cout << "Hello World" << std::endl;

The statement shows cout followed by the insertion operator << (that helps insert data into the output stream), followed by the string literal “Hello World” to be inserted, followed by a newline in the form of std::endl (pronounced “standard end-line”).

The usage of cin is simple, too, and as cin is used for input, it is accompanied by the variable you want to be storing the input data in:

std::cin >> Variable;

Thus, cin is followed by the extraction operator >> (extracts data from the input stream), which is followed by the variable where the data needs to be stored. If the user input needs to be stored in two variables, each containing data separated by a space, then you can do so using one statement:

std::cin >> Variable1 >> Variable2;

Note that cin can be used for text as well as numeric inputs from the user, as shown in Listing 2.6.

Listing 2.6. Use cin and cout to Display Number and Text Input by User

 1: #include <iostream>
 2: #include <string>
 3: using namespace std;
 5: int main()
 6: {
 7:    // Declare a variable to store an integer
 8:    int InputNumber;
10:    cout << "Enter an integer: ";
12:    // store integer given user input
13:    cin >> InputNumber;
15:    // The same with text i.e. string data
16:    cout << "Enter your name: ";
17:    string InputName;
18:    cin >> InputName;
20:    cout << InputName << " entered " << InputNumber << endl;
22:    return 0;
23: }


Enter an integer: 2011
Enter your name: Siddhartha
Siddhartha entered 2011

This is a very simple example of how basic input and output work in C++. Don’t worry if the concept of variables is not clear to you as it is explained in good detail in the following Lesson 3, “Using Variables, Declaring Constants.”

  • + Share This
  • 🔖 Save To Your Account