This program allows interaction with the user by displaying output and receiving input.

There are two important streams that you need to know: cin & cout

cout

cout sends an output to the screen and follows an insertion operator called <<. This inserts the data data and anything precedes it.

For example, cout << "Hello";

Multiple insertions are chainable in a single statement: cout << "I like " << fruit << " and my favorite subject is " << subject;

Assuming the variables initialized are string fruit, subject = "apple", "math", “

cin

cin gets an input from the user and returns the input to a variable when followed with an extraction operator >> almost similar to cout except the operators are different.

For example,

int age;
cin >> age;

In this example, we receive the input and assign it to variable age. During the user interaction, it is awaiting for an input response until after the user confirms their input through hitting enter on the keyboard. The program yields until this user input operation is finished.

If cin extracts an input with spaces (whitespaces, tabs, new-line, ..), the input has segments, which means that each segment of the input is separated and assigned to a value.

Let’s say you input 190 304 in the terminal and assign them to two variables, each variable have an assignment based on the order of variables after the extraction operator.

int x, y;
 
cout << "Enter two values:";
cin >> x >> y;
 
cout << "First value: " >> x >> "Second value: " >> y; // e.g. 3, 4
// First value: 3 Second value: 4

getline

getline is another function almost similar to cin except it extracts the entire string of the user input. The function is slightly different without the extraction operator.

getline(cin, variable)

Assigning the input to variable will give the output there. Keep in mind that the type of the variable must be string.

If getline is after cin, you must call cin.ignore().

string aString;
 
cout << "type one word only: ";
cin >> aString;
cout << "you said: " << aString;
cin.ignore();
cout << "type an entire sentence: ";
getline(cin, aString);
cout << "you said: " << aString;

NOTE: string is a compound type and must be declared with a library before initializing a string variable. See Strings in C++ for more information.