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.
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
using namespace std;
void main() {
int n;
cout << "Enter an integer: ";
cin >> n; // Taking input
cout << "The number is: " << n;
}
Enter an integer: 5
The number is: 5
The number is: 5
Note:
- The header file iostream that provides basic input and output services of C++ programs.
- 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
using namespace std;
void main() {
char c;
cout << "Enter a Character: ";
cin >> c; // Taking input
cout << "The Character is: " << n;
}
Enter a Character: a
The Character is: 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
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;
}
Enter a Character and a Number: B
25
Character: B
Number: 8
25
Character: B
Number: 8
0 Comments
if you have any doubt in programming concept please let me know