The Wayback Machine - https://web.archive.org/web/20240826130753/https://www.geeksforgeeks.org/cin-in-c/
Open In App

cin in C++

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The cin object in C++ is an object of class iostream. 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. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.

Program 1:

Below is the C++ program to implement cin object:

C++
// C++ program to demonstrate the
// cin object
#include <iostream>
using namespace std;

// Driver Code
int main()
{
    string s;

    // Take input using cin
    cin >> s;

    // Print output
    cout << s;

    return 0;
}

 
 

Input: 


 

Output:

Program 2:

Multiple inputs using the extraction operators(>>) with cin. Below is the C++ program to take multiple user inputs:
 

C++
// C++ program to illustrate the take
// multiple input
#include <iostream>
using namespace std;

// Driver Code
int main()
{
    string name;
    int age;

    // Take multiple input using cin
    cin >> name >> age;

    // Print output
    cout << "Name : " << name << endl;
    cout << "Age : " << age << endl;

    return 0;
}

 
 

Input:


 

Output:


 The cin can also be used with some member functions which are as follows:

cin.getline(char *buffer, int N):

It reads a stream of characters of length N into the string buffer, It stops when it has read (N – 1) characters or it finds the end of the file or newline character(\n). Below is the C++ program to implement cin.getline():
 

C++
// C++ program to illustrate the use
// of cin.getline
#include <iostream>
using namespace std;

// Driver Code
int main()
{
    char name[5];

    // Reads stream of 3
    // characters
    cin.getline(name, 3);

    // Print output
    cout << name << endl;

    return 0;
}

Input:
 


 

Output:


 

cin.get(char& var):

It reads an input character and stores it in a variable.  Below is the C++ program to implement cin.get():

C++
// C++ program to illustrate the use
// of cin.get()
#include <iostream>
using namespace std;

// Driver Code
int main()
{
    char ch[30];
    cin.get(ch, 25);

    // Print ch
    cout << ch;
}

Input:

Output:


 

cin.read(char *buffer, int N):

Reads a stream of characters of length N. Below is the C++ program to implement cin.read():

C++
// C++ program to illustrate the use
// of cin.read()
#include <iostream>
using namespace std;

// Driver Code
int main()
{
    char gfg[20];

    // Reads stream of characters
    cin.read(gfg, 10);

    // Print output
    cout << gfg << endl;

    return 0;
}

Input:


 


 

Output:


 


 

cin.ignore():


 

It ignores or clears one or more characters from the input buffer. Below is the C++ program to implement cin.ignore():

C++
// C++ program to illustrate the use
// of cin.ignore()
#include <iostream>

// used to get stream size
#include <ios>

// used to get numeric limits
#include <limits>
using namespace std;

// Driver Code
int main()
{
    int x;
    char str[80];
    cout << "Enter a number andstring:\n";
    cin >> x;

    // clear buffer before taking
    // new line
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // Input a string
    cin.getline(str, 80);
    cout << "You have entered:\n";
    cout << x << endl;
    cout << str << endl;

    return 0;
}

 
 

Input:
 


 

Output:


 


 

Explanation: In the above program if cin.ignore() has not been used then after entering the number when the user presses the enter to input the string, the output will be only the number entered. The program will not take the string input. To avoid this problem cin.ignore() is used, this will ignore the newline character.



Previous Article
Next Article

Similar Reads

cin get() in C++ with Examples
cin.get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (&gt;&gt;) terminates when whitespace is found. However, cin.get() reads a string with the whitespace. Syntax: cin.get(string_name, size); Example 1: // C++ program to demonstrate cin.get() #include &lt;iostream&gt; using
1 min read
Problem with getline() after cin &gt;&gt;
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage. Program 1: Below is the C++ program
2 min read
Cin-Cout vs Scanf-Printf
Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”. Let us create a dummy input file containing a line with 16 bytes followed by a newline and having 1000000 such lines, making a file of
3 min read
Using return value of cin to take unknown number of inputs in C++
Consider a problem where we need to take an unknown number of integer inputs. A typical solution is to run a loop and stop when a user enters a particular value. How to do it if we are not allowed to use if-else, switch-case, and conditional statements? The idea is to use the fact that 'cin &gt;&gt; input' is false if the non-numeric value is given
2 min read
How to Redirect cin and cout to Files in C++?
In C++, we often ask for user input and read that input using the cin command and for displaying output on the screen we use the cout command. But we can also redirect the input and output of the cin and cout to the file stream of our choice. In this article, we will look at how to redirect the cin and cout to files in C++. Redirecting cin and cout
2 min read
How to Take std::cin Input with Spaces?
In C++, std::cin is used to accept the input from the standard input device. By default, the delimiter used by std::cin to separate input is a whitespace. In this article, we will learn how to take std::cin input with spaces in C++. Example: Input: Hey! Geek Welcome to GfG //input with spacesOutput: Input Entered: Hey! Geek Welcome to GfGstd::cin I
2 min read
How to Use cin.fail() Method in C++?
In C++, the cin.fail() method is a part of &lt;iostream&gt; library that is used to check whether the previous input operation has succeeded or not by validating the user input. In this article, we will learn how to use cin.fail() method in C++. Example: Input: Enter an integer: aOutput: Invalid Input. Please Enter an Integer. C++ cin.fail() Functi
2 min read
cin.clear() function in C++
The cin.clear() function in C++ is a member function of the std::istream class, which is used to clear the error flags on the cin stream. When an input operation fails (for example, due to incorrect data type input), the cin stream enters a fail state, and further input operations are blocked until the error state is cleared. The cin.clear() functi
4 min read
cin.ignore() Function in C++
The cin.ignore() function in C++ is a member function of the std::istream. It is used to ignore (or discard) certain number of characters from the input buffer. This function is very useful when we have to deal with leftover characters in the input stream that could interfere with subsequent input operations, such as newlines or other delimiters. I
3 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read