[c++] When and why do I need to use cin.ignore() in C++?

I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:

cin.ignore(256, '\n');

before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore() line and how can I predict when I will need to use cin.ignore()?

Here is the program I wrote:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num;
    string mystr;

    cout << "Please enter a number: " << "\n";
    cin >> num;
    cout << "Your number is: " << num << "\n";
    cin.ignore(256, '\n'); // Why do I need this line?
    cout << "Please enter your name: \n";
    getline (cin, mystr);
    cout << "So your name is " << mystr << "?\n";
    cout << "Have a nice day. \n";

}

This question is related to c++ cin getline ignore

The answer is


Short answer

Why? Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.

When? When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.

Now a detailed answer.

Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n. Now cin picks up 256 and removes it from the stream and \n still remaining in the stream. Now next when you enter your name, let's say Raddicus, the new contents of the stream is \nRaddicus.

Now here comes the catch. When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream. So on calling new line, getline reads and discards \n from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.

Now, how does cin.ignore help here?

According to the ignore documentation extract from cplusplus.com-

istream& ignore (streamsize n = 1, int delim = EOF);

Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.

So, cin.ignore(256, '\n');, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).

Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n').

Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.


As pointed right by many other users. It's because there may be whitespace or a newline character.

Consider the following code, it removes all the duplicate characters from a given string.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    cin.ignore(); //Notice that this cin.ignore() is really crucial for any extra whitespace or newline character
    while(t--){
        vector<int> v(256,0);
        string s;
        getline(cin,s);
        string s2;
        for(int i=0;i<s.size();i++){
            if (v[s[i]]) continue;
            else{
                s2.push_back(s[i]);
                v[s[i]]++;
            }
        }
        cout<<s2<<endl;
    }
    return 0;
}

So, You get the point that it will ignore those unwanted inputs and will get the job done.


It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.


You're thinking about this the wrong way. You're thinking in logical steps each time cin or getline is used. Ex. First ask for a number, then ask for a name. That is the wrong way to think about cin. So you run into a race condition because you assume the stream is clear each time you ask for a input.

If you write your program purely for input you'll find the problem:

void main(void)
{
    double num;
    string mystr;

    cin >> num;
    getline(cin, mystr);

    cout << "num=" << num << ",mystr=\'" << mystr << "\'" << endl;
}

In the above, you are thinking, "first get a number." So you type in 123 press enter, and your output will be num=123,mystr=''. Why is that? It's because in the stream you have 123\n and the 123 is parsed into the num variable while \n is still in the stream. Reading the doc for getline function by default it will look in the istream until a \n is encountered. In this example, since \n is in the stream, it looks like it "skipped" it but it worked properly.

For the above to work, you'll have to enter 123Hello World which will properly output num=123,mystr='Hello World'. That, or you put a cin.ignore between the cin and getline so that it'll break into logical steps that you expect.

This is why you need the ignore command. Because you are thinking of it in logical steps rather than in a stream form so you run into a race condition.

Take another code example that is commonly found in schools:

void main(void)
{
    int age;
    string firstName;
    string lastName;

    cout << "First name: ";
    cin >> firstName;

    cout << "Last name: ";
    cin >> lastName;

    cout << "Age: ";
    cin >> age;

    cout << "Hello " << firstName << " " << lastName << "! You are " << age << " years old!" << endl;
}

The above seems to be in logical steps. First ask for first name, last name, then age. So if you did John enter, then Doe enter, then 19 enter, the application works each logic step. If you think of it in "streams" you can simply enter John Doe 19 on the "First name:" question and it would work as well and appear to skip the remaining questions. For the above to work in logical steps, you would need to ignore the remaining stream for each logical break in questions.

Just remember to think of your program input as it is reading from a "stream" and not in logical steps. Each time you call cin it is being read from a stream. This creates a rather buggy application if the user enters the wrong input. For example, if you entered a character where a cin >> double is expected, the application will produce a seemingly bizarre output.


When you want to throw away a specific number of characters from the input stream manually.

A very common use case is using this to safely ignore newline characters since cin will sometimes leave newline characters that you will have to go over to get to the next line of input.

Long story short it gives you flexibility when handling stream input.


Ignore function is used to skip(discard/throw away) characters in the input stream. Ignore file is associated with the file istream. Consider the function below ex: cin.ignore(120,'/n'); the particular function skips the next 120 input character or to skip the characters until a newline character is read.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to cin

When and why do I need to use cin.ignore() in C++? Checking cin input stream produces an integer cin and getline skipping input Multiple inputs on one line Why would we call cin.clear() and cin.ignore() after reading input? How to cin Space in c++? How do I flush the cin buffer?

Examples related to getline

When and why do I need to use cin.ignore() in C++? Using getline() with file input in C++ Using getline() in C++ c++ Read from .csv file cin and getline skipping input Why is reading lines from stdin much slower in C++ than Python? Going through a text file line by line in C reading a line from ifstream into a string variable

Examples related to ignore

When and why do I need to use cin.ignore() in C++? Git - Ignore files during merge How to remove files that are listed in the .gitignore but still on the repository? git ignore vim temporary files Git diff -w ignore whitespace only at start & end of lines How to git ignore subfolders / subdirectories? How do I configure git to ignore some files locally? Conditionally ignoring tests in JUnit 4 Is there an ignore command for git like there is for svn? How do I make Git ignore file mode (chmod) changes?