C++ cin.ignore Use of ()

The function of CIN. Sync () is to clear the buffer, while cin. Ignore () is also used to delete the data in the buffer, but it has more accurate control over the deleted data in the buffer.
Cin. Ignore () can be used if you want to take only one part of the buffer and discard the other.
cin.ignore(int intExp, char chExp);
Where intExp is an integer expression, or it can be an integer value that represents the maximum number of characters that can be ignored in a line, such as intExp=100; There is also a parameter, chExp, which is a character expression. Ignore () if you come across a character that equals chEXP, and if you don’t get chEXP after ignoRE100, just stop ignore(), so 100 is the maximum number of characters that ignore().
here are some examples

#include<iostream>
#include<cstdlib>
int main()
{
  int ival1 = 0, ival2 = 0;
  std::cin >> ival1;
  std::cin.ignore(100, '\n');
  std::cin >> ival2;
  std::cout << "ival1 = " << ival1 << std::endl;
  std::cout << "ival2 = " << ival2 << std::endl;
  system("pause");
  return 0;
}


After you press Enter, Ival1 receives 12, the rest is cleared, because Enter is itself a blank line, and then the input stream will wait for the second input to assign a value to ival2. The if there is no middle the STD: : cin. Ignore (100), '\ n') , will not wait for the second input, output ival1 = 12 ival2 = 34 directly:

Ignore (2, '\n')
STD ::cin. Ignore (100, ‘\n’) STD ::cin. Ignore (2, ‘\n’), after ival1 receives 12, ignore will clear two characters:

Why is iVAL2 4 instead of 78?
Because the IO objects we use are cin cout manipulation char data, no matter what data we input, cin cout will be transformed into char for processing, for example, we want to output the value of a plastic variable, then before the output, cout will turn the value of the variable into characters, in the output (C++ Primer Plus In essence, the c + + insertion operator adjusts its behaviors to fit the type of data that follows it.), so ignore to clear out a space above and one character at a time, so the remaining 4, 56, 78, the buffer so ival2 is equal to 4.
(3) If cin. Ignore () does not give the parameter, the default parameter is cin. Ignore (1,EOF), that is, one character before EOF will be cleared out.

Read More: