C++ Input

In this tutorial, we will learn about cin and also give some examples. cin is an object of the input stream that is used input from the input device e.g keyboard.

In C++, The cin object along with the >> operator (extraction operator), is used to input from the device.

Example1: Integer Input

#include "iostream"
using namespace std;
void main() {
int n;
cout << "Enter an integer: ";
cin >> n; // Taking input
cout << "The number is: " << n;
}
Output 
 
Enter an integer: 5
The number is: 5

Note:
  1. The header file iostream that provides basic input and output services of C++ programs.
  2. The cin object is defined inside the std namespace. If this namespace is not used, Computer cannot identify cin and therefore it throws errors.

In the program, we used

cin >> n;

to take input from the user. The input is stored in the variable n. We use the >> operator along with cin to take input.

Example2: Character Input

#include "iostream"
using namespace std;
void main() {
char c;
cout << "Enter a Character: ";
cin >> c; // Taking input
cout << "The Character is: " << n;
}
Output 
 
Enter a Character: a
The Character is: a

Example4: Taking Multiple Inputs

#include "iostream"
using namespace std;
void main() {
char c;
int n;
cout << "Enter a Character and a Number: ";
cin >> c >> n;
cout << "Character: " << c << endl;
cout << "Number: " << n;
}
Output 
 
Enter a Character and a Number: B
25
Character: B
Number: 8

Post a Comment

0 Comments