title: When and why do I need to use cin.ignore() in C++?
body: <p>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: </p>
  
  <pre><code>cin.ignore(256, '\n');
  </code></pre>
  
  <p>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 <code>cin.ignore()</code> line and how can I predict when I will need to use <code>cin.ignore()</code>? </p>
  
  <p>Here is the program I wrote:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  int main()
  {
      double num;
      string mystr;
  
      cout &lt;&lt; "Please enter a number: " &lt;&lt; "\n";
      cin &gt;&gt; num;
      cout &lt;&lt; "Your number is: " &lt;&lt; num &lt;&lt; "\n";
      cin.ignore(256, '\n'); // Why do I need this line?
      cout &lt;&lt; "Please enter your name: \n";
      getline (cin, mystr);
      cout &lt;&lt; "So your name is " &lt;&lt; mystr &lt;&lt; "?\n";
      cout &lt;&lt; "Have a nice day. \n";
  
  }
  </code></pre>