C++ cin

The cin object in C++ is an object of class istream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin.

cin declaration

extern istream cin;

It is defined in <iostream> header file.

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 which means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for output.

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. The general syntax is:

cin >> varName;

The extraction operator can be used more than once to accept multiple inputs as:

cin >> var1 >> var2 >> … >> varN;

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 store 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.
  • 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 nonzero value if the end of file (eof) is reached.

Example 1: cin with extraction operator:

#include <iostream>

using namespace std;

int main()
{
	int x, y, z;
	
	/* For single input */
	cout << "Enter a number: ";
	cin >> x;
	
	/* For multiple inputs*/
	cout << "Enter 2 numbers: ";
	cin >> y >> z;
	
	cout << "Sum = " << (x+y+z);
	return 0;
}

When you run the program, a possible output will be:

Enter a number: 9
Enter 2 numbers: 1 5
Sum = 15

Example 2: cin with member function:

#include <iostream>

using namespace std;

int main()
{
	char name[20], address[20];
	
	cout << "Name: ";
	cin.getline(name, 20);
	
	cout << "Address: ";
	cin.getline(address, 20);
	
	
	cout << endl << "You entered " << endl;
	cout << "Name = " << name << endl;
	cout << "Address = " << address << endl;
	
	return 0;
}

When you run the program, a possible output will be:

Name: Sherlock Holmes
Address: Baker Street, UK

You entered
Name = Sherlock Holmes
Address = Baker Street, UK

Check these related library functions as well: