C++ Basic Input/Output | Display output in C++

C++ Basic Input/Output | Display output in C++

There are different statements and functions to Display output in C++. They are as follows:

  • cout
  • write()
  • put()

1. cout statement in C++

We can use  cout statement in C++ to display output.  It can be used to display a value of any primary data type. like int, float, char etc.
cout is followed by <<(insertion operator ) further followed by the variable or the constant whose value we want to display.
We need to include header file <iostream> and import namespace std in our program to use cout.
Syntax:

cout<<var;

Here, var refers to the variable or constant whose value should be displayed.

//Program to demonstrate the use of cout statement in C++. 
#include<iostream> 
using namespace std;
int main()
{
 int n;
 cout<<"Enter an integer value=";
 cin>>n;
 cout<<"\nn="<<n;
 return 0;
}

Output

Enter an integer value=100
n=100

2. write() function in C++

write() function in C++ is used along with  cout to display specific number of characters from a string or output file stream object to store data to a data file.
We need to include header file <iostream> and import namespace std in our program to use it.
Syntax:

write(s,n);

Here, s is the string variable or constant.
n is the number of characters to be displayed from the string variable.

//Program to demonstrate the use of write statement.
#include<iostream> 
using namespace std;
int main()
{
 char n[30];
 cout<<"\nEnter a string value=";
 cin>>n;
 cout<<"\nValue=";
 cout.write(n,5);  //First 5 character are displayed.
 return 0;
}

Output

Enter a string value=Lovejot
Name=Lovej

3. put()  function in C++

put() function in C++ is also used with  cout statement to display a character variable/constant. It can also be used with output file stream object to put one  character into a text file.

We need to include header file <iostream> and import namespace std in our program to use it.

Syntax:

 cout.put(charvar);

Here, charvar refers to the character variable/constant whose value should be displayed.

//Program to demonstrate the use of put() function.

#include<iostream> 
using namespace std;
int main()
{
 char n;
 cout<<"\nEnter a character=";
 cin.get(n);
 cout<<"\ncharacter=";
 cout.put(n);
 return 0;
}

Output

Enter a character=A
character=A
 
Spread the love
Lesson tags: C++ Basic Input/Output, cout statement in C++, display output in c, put()  function in C++, write() function in C++
Back to: C++ Programming Notes
Spread the love