Professional Documents
Culture Documents
C++ Cin: in This Tutorial, We Will Learn About The Cin Object in C++ With The Help of Examples
C++ Cin: in This Tutorial, We Will Learn About The Cin Object in C++ With The Help of Examples
In this tutorial, we will learn about the cin object in C++ with the help of
examples.
The cin object is used to accept input from the standard input device i.e.
keyboard. It is defined in the iostream header file.
Example
#include <iostream>
using namespace std;
int main() {
int num;
return 0;
}
Run Code
Output
Enter a number: 25
You entered: 25
cin Syntax
The syntax of the cin object is:
Here,
int num;
cin >> num;
The >> operator can also be used more than once in the same statement to
accept multiple inputs:
int main() {
int num1, num2, num3;
return 0;
}
Run Code
Output
Enter a number: 9
Enter 2 numbers:
1
5
Sum = 15
cin with Member Functions
The cin object can also be used with other member functions such
as getline() , read() , etc. Some of the commonly used member functions are:
cin.get(char &ch): Reads an input character and stores it in ch .
cin.read(char *buffer, int n): Reads n bytes (or until the end of the file)
from the stream into the buffer .
cin.ignore(int n): Ignores the next n characters from the input stream.
cin.eof(): Returns a non-zero value if the end of file ( eof ) is reached.
Example 2: cin with Member Functions
#include <iostream>
using namespace std;
int main() {
char name[20], address[20];
cin.getline(address, 20);
return 0;
}
Run Code
Output
You entered
Name = Sherlock Holmes
Address = Baker Street, UK
cin Prototype
The prototype of cin as defined in the iostream header file is:
The cin object in C++ is an object of class istream . It is associated with the
standard C input stream stdin .
The cin object is ensured to be initialized during or before the first time an
object of type ios_base::Init is constructed.
After the cin object is constructed, cin.tie() returns &cout . This means that
any formatted input operation on cin forces a call to cout.flush() if any
characters are pending for output.