C++ Practical Programs
Aim
Write a C++ programs to illustrate the concept of console I/O operations
Solution
In C++ Programming, the console IO operations are performed using the header file iostream.h. This header file provides two objects cin and cout to perform input and output operations respectively.
There are mainly two types of consol IO operations.
- 1. Unformatted consol IO -
- 2. Formatted consol IO
Unformatted console IO operations
We use the following built-in functions to perform operations of type unformatted consol IO operations.
⇢ get( ) and put( )
The get( ) is a method of cin object used to input a single character from the standard input device (keyboard). Its main property is that it allows wide spaces and newline character. The get() function does not have any return value (void get( )).
The put() is a method of cout object and it is used to print the specified character on standard output device (monitor).
#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"Press any key: ";
ch = cin.get();
cout << "You have pressed: ";
cout.put(ch);
return 0;
}
Result
⇢ getline(char *buffer,int size) and write(char * buffer, int n)
The getline(char *buffer,int size) is a method of cin object and it is used to input a string with multiple spaces.
The write(char * buffer, int n) is a method of cout object and it is used to read n character from buffer variable.
#include <iostream>
using namespace std;
int main()
{
char ch[20];
cout<<"What is your favourite website: ";
cin.getline(ch, 20);
cout <<endl<< "visit: www.";
cout.write(ch, 17);
cout<<".com"<<endl;
return 0;
}
Result
⇢ cin and cout objects
The cin is the object used to take input value of any variable of any type. It must be used with an overloaded operator “>>”.
The cout is an object used to print string and variable values. It must be used with an overloaded operator “<<”.
#include <iostream>
using namespace std;
int main()
{
int variable_int;
float variable_float;
char variable_char;
cout<<"Enter any integer number: ";
cin>>variable_int;
cout<<"Enter any floating point number: ";
cin>>variable_float;
cout<<"Enter any character: ";
cin>>variable_char;
cout <<endl<< "Integer = "<<variable_int<<endl;
cout <<endl<< "Floating Point = "<<variable_float<<endl;
cout <<endl<< "Character = "<<variable_char<<endl;
return 0;
}
Result
Formatted console IO operations
The C++ programming language provides the following built-in functions to display the output in formatted form. These built-in functions are available in the header file iomanip.h.
⇢ setw(int) and setfill(char)
The setw( int ) is a method used to set width of the output.
The setfill(char) is a method used to fill specified character at unused space.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x=10;
cout<<setw(10);
cout<<x<<endl;
cout<<setw(10)<<setfill('*')<<x<<endl;
return 0;
}