
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Hello World
- C++ Omitting Namespace
- C++ Tokens
- C++ Constants/Literals
- C++ Keywords
- C++ Identifiers
- C++ Data Types
- C++ Numeric Data Types
- C++ Character Data Type
- C++ Boolean Data Type
- C++ Variable Types
- C++ Variable Scope
- C++ Multiple Variables
- C++ Input Output Operations
- C++ Basic Input/Output
- C++ Cin
- C++ Cout
- C++ Manipulators
- Type System & Data Representation
- C++ Modifier Types
- C++ Storage Classes
- C++ Constexpr Specifier
- C++ Numbers
- C++ Enumeration
- C++ Enum Class
- C++ References
- C++ Date & Time
- C++ Operators
- C++ Operators
- C++ Arithmetic Operators
- C++ Relational Operators
- C++ Logical Operators
- C++ Bitwise Operators
- C++ Assignment Operators
- C++ sizeof Operator
- C++ Conditional Operator
- C++ Comma Operator
- C++ Member Operators
- C++ Casting Operators
- C++ Pointer Operators
- C++ Operators Precedence
- C++ Unary Operators
- C++ Scope Resolution Operator
- C++ Control Statements
- C++ Decision Making
- C++ if Statement
- C++ if else Statement
- C++ Nested if Statements
- C++ switch Statement
- C++ Nested switch Statements
- C++ Loop Types
- C++ while Loop
- C++ for Loop
- C++ do while Loop
- C++ Foreach Loop
- C++ Nested Loops
- C++ Jump Statements
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ Return Values
- C++ Strings
- C++ Strings
- C++ Loop Through a String
- C++ String Length
- C++ String Concatenation
- C++ String Comparison
- C++ Functions
- C++ Functions
- C++ Multiple Function Parameters
- C++ Recursive Function
- C++ Function Overloading
- C++ Function Overriding
- C++ Default Arguments
- C++ Arrays
- C++ Arrays
- C++ Multidimensional Arrays
- C++ Pointer to an Array
- C++ Passing Arrays to Functions
- C++ Return Array from Functions
- C++ Structure & Union
- C++ Structures
- C++ Unions
- C++ Class and Objects
- C++ Object Oriented
- C++ Classes & Objects
- C++ Class Member Functions
- C++ Class Access Modifiers
- C++ Static Class Members
- C++ Static Data Members
- C++ Static Member Function
- C++ Inline Functions
- C++ this Pointer
- C++ Friend Functions
- C++ Pointer to Classes
- C++ Constructors
- C++ Constructor & Destructor
- C++ Default Constructors
- C++ Parameterized Constructors
- C++ Copy Constructor
- C++ Constructor Overloading
- C++ Constructor with Default Arguments
- C++ Delegating Constructors
- C++ Constructor Initialization List
- C++ Dynamic Initialization Using Constructors
- C++ Inheritance
- C++ Inheritance
- C++ Multiple Inheritance
- C++ Multilevel Inheritance
- C++ Object-oriented
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Virtual Function
- C++ Pure Virtual Functions & Abstract Classes
- C++ Design Patterns
- C++ Creational Design Patterns
- C++ Singleton Design Pattern
- C++ Factory Method Design Pattern
- C++ Abstract Factory Pattern
- C++ Prototype Design Pattern
- C++ Structural Design Patterns
- C++ File Handling
- C++ Files and Streams
- C++ Reading From File
- C++ Advanced
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
- C++ Socket Programming
- C++ Concurrency
- C++ Advanced Concepts
- C++ Lambda Expression
- C++ unordered_multiset
Cin in C++
The predefined object cin is an instance of istream class that accepts the user input. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin object is used in conjunction with the stream extraction operator (>>) that extracts the data from the input stream and stores the extracted data in a variable.
The syntax for using the cin object with a single variable and multiple variables is given below −
// For single variable cin >> variable_name; or // For multiple variables cin >> variable1 >> variable2 >> ... >> variableN; where, >> is the extraction operator. variable_name, variable1, variable2, ..., variableN are the variable names where we store the input values.
Read this chapter to get a good understanding of how the cin object works. We have used plenty of examples to explain all of its features in detail.
Taking User Input with cin
The following example demonstrates how to take a single integer and multiple integers as input using cin to calculate the sum of the numbers −
#include <iostream> using namespace std; int main(){ int num1; cout << "Enter number num1: "; cin >> num1; cout << "Num1: " << num1 << endl; int num2, num3; cout << "Enter the numbers num2 and num3: "; cin >> num2 >> num3; cout << "Num2: " << num2 << ", Num3: " << num3 << "\n" << "Sum: " << num1 + num2 + num3 << endl; return 0; }
The output of the above code is as follows −
Enter number num1: 2 Num1: 2 Enter the numbers num2 and num3: 2 5 Num2: 2, Num3: 5 Sum: 9
Taking Array Input with cin
This example demonstrated how to take an array as input using cin:
#include <iostream> using namespace std; int main(){ int arr[5]; int n = 5; cout << "Enter " << n << " array elements: "; for (int i = 0; i < n; i++){ // Taking array elements input cin >> arr[i]; } cout << "Array elements: "; for (int i = 0; i < n; i++){ cout << arr[i] << " "; } return 0; }
The output of the above code is as follows −
Enter 5 array elements: 1 2 3 4 5 Array elements: 1 2 3 4 5
C++ cin Object Functions
Below is a table of most commonly used functions of C++ cin object −
Functions | Definition |
---|---|
cin.get() | The cin.get() function reads a single character including whitespace from input stream. |
cin.getline() | It reads a line of text from user input along with whitespaces until it reaches end of the line or newline character. |
cin.read() | You can specify the number of characters you want to read from input stream using cin.read() function. |
cin.putback() | The cin.putback() function puts a character back into the input stream that was removed after using get() function to read the character. |
cin.peek() | It looks at the next character in the input stream without removing it unlike get() function that removes the character. |
cin.good() | It checks the state of input stream and returns true if the input stream is in a good state with no errors. |
cin.bad() | It checks the state of input stream and returns true if an error occurs in the stream that can not be recovered. |
cin.fail() | It returns true for failed operations on the input stream. |
cin.clear() | It clears the error flags of the stream and reset it to good state. |
cin.ignore() | The cin.ignore() function is used to skip and discard characters from the input buffer so they are not read by the next input operation. |
cin.gcount() | It returns the count of characters extracted by the last unformatted input operation including whitespaces. |
cin.seekg() | It is used in file handling to set the position of the get pointer in the input stream. It is generally used with file streams (ifstream). |
cin.eof() | It returns true upon reaching end of file in the input stream. |
cin.rdbuf() | It returns the stream buffer object of cin that can be used to read from or redirect the input stream directly. |
Here are the example codes of each member function listed above in the table −
In this example, we have used the cin.get() function to read the first character of input stream −
#include <iostream> using namespace std; int main(){ cout << "Enter any character: "; char ch = cin.get(); cout << "Entered character: '" << ch << "'" << endl; char ch2 = cin.get(); cout << "Entered character: '" << ch2 << "'" << endl; return 0; }
The output of the above code is given below. Here we have used the get() function twice. The first time it return the character 'a' and second time it returns a blank space.
Enter any character: a b c Entered character: 'a' Entered character: ' '
Here is an example of cin.getline() function to read an entire line until it reaches a newline character.
#include <iostream> using namespace std; int main() { char sent[50]; cout << "Enter any sentence: "; cin.getline(sent, 50); cout << "Entered Sentence: " << sent << endl; return 0; }
The output of the above code is as follows −
Enter any sentence: Welcome to Tutorialspoint. Entered Sentence: Welcome to Tutorialspoint.
The following example reads first 5 characters of input stream using cin.read() function.
#include <iostream> using namespace std; int main(){ char buffer[6]; cout << "Enter a sentence: "; cin.read(buffer, 5); buffer[5] = '\0'; cout << "First 5 characters: " << buffer << endl; return 0; }
The output of the above code is as follows −
Enter at least 5 characters: Monkey D. Luffy First 5 characters: Monke
Here is an example of putback() function that inserts back the first character read and removed by the get() function −
#include <iostream> using namespace std; int main() { cout << "Enter a character: "; char ch = cin.get(); cout << "Entered character: " << ch << endl; cin.putback(ch); char ch2 = cin.get(); cout << "Read character again: " << ch2 << endl; return 0; }
The output of the above code is as follows −
Enter a character: Tutorialspoint Entered character: T Read character again: T
In this example, the peek() function looks at the next character in the input stream but does not remove it, unlike get() function.
#include <iostream> using namespace std; int main() { cout << "Enter a number: "; char next = cin.peek(); cout << "Current character in input buffer: " << next << endl; int num; cin >> num; cout << "Number entered: " << num << endl; return 0; }
The output of the above code is as follows −
Enter a number: 978 Current character in input buffer: 9 Number entered: 978
In this example, we are validating the user input for an integer. For integer input, it prints the integer and for non-integer inputs, it prints a message of invalid input.
#include <iostream> using namespace std; int main() { int num; cout << "Enter an integer: "; cin >> num; if (cin.good()) { cout << "Valid input. Given number: " << num << endl; } else { cout << "Invalid input. Input number is not an integer" << endl; } return 0; }
The output of the above code is as follows −
Enter an integer: 345 Valid input. Given number: 345 Enter an integer: abcd Invalid input. Input number is not an integer
The following example demonstrates the use of cin.bad(). It returns true only for >non-recoverable errors. Here we have used a string as input in place of a number and still this program doesn't give an error.
#include <iostream> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; if (cin.bad()) { cout << "Error occurred!" << endl; } else { cout << "No error. Given number: " << num << endl; } return 0; }
The output of the above code is as follows −
Enter a number: abcd No error. Given number: 0
In this example, the cin.fail() returns true if the input is not an integer value as it represents a failed operation −
#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; if (cin.fail()) { cout << "Invalid input. Enter a number." << endl; } else { cout << "Entered age: " << age << endl; } return 0; }
The output of the above code is as follows −
Enter your age: 23 Entered age: 23 Enter your age: Tp Invalid input. Enter a number.
The following example clears the error flags when user inputs a non-integer value −
#include <iostream> using namespace std; int main(){ int num; cout << "Enter a number: "; cin >> num; if (cin.fail()){ cout << "Invalid input. Clearing error..." << endl; cin.clear(); cout << "Error flags cleared!" << endl; } else { cout << "Input successful: " << num << endl; } return 0; }
The output of the above code is as follows −
Enter a number: 45 Input successful: 45 Enter a number: Tutorialspoint Invalid input. Clearing error... Error flags cleared!
In this example, we are taking two inputs from user. Without ignore() function, it returns the output by taking just one input from user.
#include <iostream> #include <string> using namespace std; int main(){ int age; string name; cout << "Enter your age: "; cin >> age; // Ignores the newline character left by the last input cin.ignore(); cout << "Enter your name: "; getline(cin, name); // Now this works as expected cout << "Your age is: " << age << endl; cout << "Your name is: " << name << endl; return 0; }
The output of the above code is as follows:
Enter your age: 57 Enter your name: Viper Your age is: 57 Your name is: Viper Without using ignore(): Enter your age: 57 Enter your name: Your age is: 57 Your name is:
Here is an example of cin.gcount() function returning the count of input characters including the whitespaces −
#include <iostream> using namespace std; int main() { char buffer[100]; cout << "Enter text: "; cin.getline(buffer, 100); cout << "Entered Text: " << buffer << endl; cout << "Count of characters: " << cin.gcount() << endl; return 0; }
The output of the above code is as follows:
Enter text: Tutorials Point Entered Text: Tutorials Point Count of characters: 16
The following example returns the input string until it reaches a whitespace or end of the file. If you are not using a file, press ctrl+d to run the code without any input, or you can use our C++ compiler to run code without giving any input.
#include <iostream> using namespace std; int main(){ string text; cout << "Enter a text: "; cin >> text; if (cin.eof()) { cout << "End of file reached!" << endl; } else { cout << "Your text: " << text << endl; } return 0; }
The output of the above code is as follows.
Enter a text: Tutorials Point Your text: Tutorials Enter a text: TutorialsPoint Your text: TutorialsPoint For empty input: Enter a text: End of file reached!
Conclusion
In this chapter, we understood the cin object and its usage along with its member functions and their respective example codes.