Basic input/output C++

Here we will discuss basic input/output(i/o) operations. C++ uses streams for input output operations. That are discuss below.

C++ cout

In C++ the standard output stream (cout) command is used to display output on standard output device i.e. LED, Monitor.

It is defined in <iostream> header file.

The C in cout is “character” & out means “output”, so cout means character output. Then insertion operator (<<) used in order to display the body of cout.

Syntax:

  1. Cout<<”body of cout”;

&

  1. Cout<<num;

Here in 1st method whatever you write in inverted commas it will display on screen.

In 2nd method without inverted commas, the data stored in variable num will be display on screen.

The insertion operator could be use many times with the combination of variables. For example:

Cout<<”My name is “<<name<<endl;

Example 1:

#include<iostream>
#include<string>
using namespace std;
void main()
{
string name = “Jack”;
cout << “My name is “ << name << endl;
system(“pause”);
}

Output:

My name is Jack

C++ cin

In C++ standard input stream (cin) object is used to accept the input from standard input device i.e. keyboard. It is defined in <iostream> header file.

In cin ‘C’ means “character” & ‘in’ means “input”, so cin means character input. Cin object is used along with extraction operator(>>) in order to store the input.

Syntax:

Cin>>input;

It is use when value asked from user & store in the variable.

The extraction operator(>>) could be use more than one time, for example:

Cin>>variable1>>variable2>>variable3;

By using extraction operator, more than one value could be store in different variables.

Example:

#include<iostream>
using namespace std;
void main()
{
int var1;
int var2;
int var3;
cout << “Enter 3 values” << endl;
cin >> var1 >> var2 >> var3;
cout << “1st value is = “ << var1 << endl;
cout << “2nd value is = “ << var2 << endl;
cout << “3rd value is = “ << var3 << endl;
cout << “Sum of these values is = “ << var1 + var2 + var3<<endl;
system(“pause”);
}

Output:

Enter 3 values
1
2
3
1st value is = 1
2nd value is = 2
3rd value is = 3
Sum of these values is = 6

 

Here in above program, user asked to enter 3 values that are stored in var1, var2 & var3 by using cin object. Then display the sum of all values.