C++ cin
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 using namespace std; int main() < int num; cout // take integer input cin >> num; cout
Output
Enter a number: 25 You entered: 25
cin Syntax
The syntax of the cin object is:
cin >> var_name;
- >> is the extraction operator.
- var_name is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc.
cin with Extraction Operator
The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input".
The cin object is used along with the extraction operator >> in order to receive a stream of characters. For example,
int num; cin >> num;
The >> operator can also be used more than once in the same statement to accept multiple inputs:
cin >> var1 >> var2 >> … >> varN;
Example 1: cin with Extraction Operator
// for single input cin >> num1;
cout << "Enter 2 numbers:" << endl;
// for multiple inputs cin >> num2 >> num3;
cout << "Sum https://www.programiz.com/cpp-programming/istream#getline-function">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.getline(char *buffer, int length): Reads a stream of characters into the string buffer , It stops when
- it has read length-1 characters or
- when it finds an end-of-line character '\n' or the end of the file eof .