C++Input and Output

IO stands for input and output, a fundamental concept of every computer program, where programs take input and produce a meaningful output. C++ provides standard objects for performing input and output operations. We will look at the different ways that we can perform IO operations.

The “iostream” header file

The IO stream file is the library that allows us to use objects like cin and cout, to read input or output data to the standard console(terminal).

We must include the “iostream” header file at the top of our code to use cin and cout.

The “std” namespace

Namespace defines the scope of access of a variable. Putting the line using namespace std at the top of the file allows us to use cin and cout without referencing the “std” namespace every time.

/* Without "using namespace std" requires std:: to be prefixed */
std::cin>>num;
std::cout<<"hello world";
/* With "using namespace std" no need to reference std:: */
cin>>num;
cout<<"hello world";

Full Example

#include<iostream>
using namespace std;
int main(){
/* now any iostream defined I/O statements will work */
cout<<"HELLO WORLD";
/* outputs: HELLO WORLD */
}

Outputting strings using cout

Using cout (pronounced see out), we can output any string to the console/terminal in C++. The output operator (<<) must be used together with cout.

/* the line below will display a message "hello world" to the terminal */
cout<<" hello world";

The strings that we display must be inside double-quotes. We can also display variables as:

cout<<myvariable;

Reading input using cin

Most programs need input data from the user to operate. Take, for instance, a calculator, which requires two numbers and one operator for an addition operation. It then performs the calculation and produces a result.

To read inputs from the user, we need to use the cin object together with the input operator (>>).

/* first define the variable to store the user input */
int num;
/* display a prompt to enter a number */
cout<<" Enter a number: ";
/* read the entered input and store it inside num */
cin>>num;
/* now num's value can be used for further processing… */

The cin statement keeps on waiting until the user enters input. The lines that come after the cin statement only run after the input is received.

Cascading Inputs and Outputs

We can chain the input (cin) and output (cout) operations in one statement using multiple IO operators.

Cascading Outputs

We can output as many strings or variables as we want by chaining the output operator (<<) as shown below.

Examples:

/* output two values */
cout<<"Hello world"<<" how are you?";
/* output a variable with other strings */
cout<<"Num 1 is "<<num1<<" and Num 2 is "<<num2;

Cascading Inputs

When we need to read two or more values, they can be chained using the operator’s input (>>) operator. The program will keep on waiting for the inputs to be received.

Please note that space or a new line must separate two or more inputs entered by the user.

Example:

/* input two values */
int num1, num2;
cout<<"Enter num1 and num2: ";
/* after user enters 5 6 */
cin>>num1>>num2;
cout<<"Num 1 is "<<num1<<" and Num 2 is "<<num2;
/* Num 1 is 5 and Num 2 is 6 */

Reading and Writing String Inputs

Strings are frequently used data types in programming. You can read a word with cin but not a line of text (including spaces, tabs) from the user. C++ provides us with methods to deal with it.

Newlines

A new line is a single character "\n" (backslash n) that we add to mark the end of every line. If there is a paragraph of text with multiple lines, it will look like this:

Hello world\n
How are you?

We can also use newline characters when outputting strings using cout:

cout<<" 1. This is the first line. \n2. This is the second line.";

It would be displayed as below in the console:

1. This is the first line.
2. This is the second line.

Reading a line of text with cin.getline()

The cin object provides a method called getline(). We can read a line of text from the user with this method:

cin.getline(variable, length);

The variable must be of the string type (character array). The second parameter is the maximum length of characters to read.

char sentence[30];
cout<<" Enter a line of text: ";
cin.getline(sentence, 30);
/* now sentence contains the entered text by the user */

“cin.getline()” vs “cin>>string”

Both are similar but cin.getline() is used for reading strings and characters but not number data types.

cin>> cannot read any whitespaces or tabs so it can read only words, numbers, or characters.

Writing a line of text with cout.write()

Just like cin.getline(), there is a similar function to output a line of text to the console.

cout.write(string, length);

It takes the string to display and the max length to output.

char string[30]="hello world!";
cout.write(string, 30);
/* displays “hello world” */

“cout.write()” vs “cout<<string”

The only difference between these two is that cout.write() can specify the length of characters to output while cout<< cannot.

char string[30]="hello world!";
cout.write(string, 20);
/* outputs a total of 20 characters "hello world" */
cout.write(string, 3);
/* outputs a total of 3 characters "hel" */
cout<<string;
/* No control over the output length! It always outputs the exactly defined string content i.e."hello world" */

Formatting Outputs

Formatting ensures that the output is presented cleanly and efficiently for the user to understand. There are different methods to format the output.

Adding New Lines

We can create a new line using \n. It is useful to visually separate statements with empty lines.

Without new lines

cout<<”*** Messages ***”<<”Message 1”<<”Message 2”;
/*
***Messages*** Message 1Message 2
*/

With new lines

cout<<”*** Messages ***\n\n”<<”Message 1\n”<<”Message 2”;
/*
***Messages***:

Message 1
Message 2
*/

Using endl

We can also use endl (stands for endline) instead of using \n.

int num1=5, num2=10;
cout<< num1 << ”\n” << num2 << ”\n”;
/* which is same as */
cout<< num1 << endl << num2 << endl;

Points to Remember

1. The iostream file must be included to use any IO operations.
2. Use the namespace std to avoid typing std::cin and std::cout every time.
3. cin takes an input from the console and stores it in a variable.
4. cout can output strings and variables to the console.
5. We can cascade either multiple inputs (>>) or output (<<) operators in one statement.
6. cin.getline() can read a line of text.
7. We can format outputs using \n and endl.

Back to: Learn C++ Programming > Input/Output in C++

Leave a Reply

Your email address will not be published. Required fields are marked *