cin.ignore() Function in C++

Last Updated : 4 May, 2026

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.

Syntax:

cin.ignore(count, delimiter);

The cin.ignore() function in C++ accepts the following two parameters:

  • count: The maximum number of characters to ignore. The default is 1.
  • delimiter:The delimiter character at which the function stops ignoring characters. The default is the newline character '\n'.

The cin.ignore() function does not return any value. Its main purpose is to discard characters from the input buffer up to the specified limit.

Example 1

In the example below, we used cin.ignore() to discard the newline character left in the input buffer after reading the integer age, ensuring that the next input (for initial) is handled correctly.

C++
#include <iostream>
using namespace std;

int main(){
    int age;
    char initial;

    // Prompt the user to enter their age
    cout << "Enter your age: ";
    cin >> age;

    // Use cin.ignore() to discard the newline character
    cin.ignore();

    // Prompt the user to enter the first letter of their name
    cout << "Enter the first letter of your name: ";
    cin >> initial;

    // Display the entered age and initial
    cout << "Your age is " << age << " and your initial is " << initial << endl;
    return 0;
}


Output

Enter your age: 10
Enter the first letter of your name: G
Your age is 10 and your initial is G
  • Time Complexity: O(n), where n is the number of characters specified by the count parameter or the position of the delimiter.
  • Auxiliary Space: O(1) as it does not involve any additional memory allocation.

Example 2

In the above example, cin.ignore(10, ' ') is used to skip up to 10 characters or until a space is encountered, that allows the program to process the next meaningful input.

C++
#include <iostream>
using namespace std;

int main(){
    cout << "Enter a sentence: ";

    // Use cin.ignore() to skip up to 10 characters or until a space is encountered.
    cin.ignore(10, ' ');
    char nextChar;

    // Read the next character from the input stream
    cin >> nextChar;

    // Output the character that was read after ignoring the specified characters
    cout << "Next character after ignoring: " << nextChar << endl;

    return 0;
}


Output

Enter a sentence: Hellowelcometo geeksforgeeks
Next character after ignoring: m
  • Time Complexity: O(n), where n is the number of characters specified by the count parameter or the position of the delimiter.
  • Auxiliary Space: O(1) as it does not involve any additional memory allocation.
Comment