When to use Cin.ignore() in C++?

Asked

Viewed 4,999 times

7

When exactly to use the cin.ignore() in a software written in C++? Why many of the times, when I’m making a big software, the readings keep bugging, sometimes if I put cin.ignore() Loosens, sometimes Wrings more.

So, what is the right way to use the cin.ignore() ?

1 answer

12


As its name already suggests, the cin.ignore() is used when you want to ignore one or more of the buffer incoming.

When exactly to use Cin.ignore() in software written in C++?

The cin.ignore() treats as delimiter the characters: \t and \n, then you will use when receiving an entry and want to ignore those characters that remained in the buffer incoming.

So, what’s the right way to use Cin.ignore() ?

In a well summarized way, you use in cases that want to ignore unread characters on buffer as I mentioned earlier.

Ex:

  1. You want to get one string user and store in a char:

    char teste[20];

  2. You will read the entry using the cin:

    cin >> teste;

  3. Assuming the user has typed teste and pressed ENTER. The teste will be received, and the \nwill remain in the buffer incoming.

  4. Using the cin.ignore() the character \nwho remain in the buffer input will be ignored.

I tried to be as brief as possible in the answer, that reference may be a complement to your understanding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.