Obeguistake61
Obeguistake61

Reputation: 33

What cin.ignore() does exactly?

I've been told by my professor that every time I use cin, I should always follow it with cin.ignore(100, '\n'). But, I never understood why?

Here is an example:

const int MAX = 200;
char input[MAX];

cout << "Enter something: ";
    cin.get(input, MAX);
    cin.ignore(100, '\n'); //why necessary?!!

Upvotes: 3

Views: 12953

Answers (2)

acheigrec
acheigrec

Reputation: 1

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

It ignores the first 100 characters, but if the function encounters '\n' before ignoring 100 characters, the function will stop discarding characters. So I assume that your professor wants you to ignore the rest of the data on the line unless it's longer than 100 characters.

Upvotes: 0

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

You don't need to use ignore every time, but it is good to use after formatted input, or in cases like yours where you only read a specified amount.

In your example, if I were to type in over 200 characters, any future input might be in for a rough surprise.

char input[200];
std::cin.get(input, 200);

After this executes, the first 200 characters were extracted, but anything after that is still left lying in the stream. It also leaves the newline ('\n') character in it. Anytime you want to extract input after this, it'll read in the remaining characters from our previous input.

This happens with formatted input, too. Take this example:

int age;
std::string name;
std::cin >> age;
std::getline(std::cin, name);

What you want is to type in an age, like 32, and a name, like "Bob". What happens is you input the age, and the program skips reading the name. When std::cin uses >> to read into variables, it leaves the '\n' character that was put into the stream by hitting enter. Then, getline reads in that newline character and stops, because it hit a newline and thinks it is done.

ignore solves this problem by discarding everything up to and including the next newline character, so that the extra input doesn't mess with future reads.

std::cin.ignore(std::numeric_limits<std::streamsize>::max());

Upvotes: 5

Related Questions